Repository navigation
Expand file tree
/
Copy pathserver.cpp
More file actions
2349 lines (2221 loc) · 90.4 KB
/
Copy pathserver.cpp
File metadata and controls
2349 lines (2221 loc) · 90.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <sync/update_coordinator.hpp>
#include <sync/server.hpp>
#include <sync/daemon_metrics.hpp>
#include <sync/control.hpp>
#include <sync/frame_receiver.hpp>
#include <sync/origin.hpp>
#include <sync/pairing.hpp>
#include <sync/render/render_supervisor.hpp>
#include <sync/websocket.hpp>
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include <uv.h>
#include <algorithm>
#include <array>
#include <cctype>
#include <cstddef>
#include <cstdint>
#include <condition_variable>
#include <cstring>
#include <iostream>
#include <limits>
#include <memory>
#include <mutex>
#include <new>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <thread>
#include <utility>
#include <vector>
namespace noisefactor::sync {
namespace {
constexpr std::size_t kMaximumSenders = 64;
constexpr std::size_t kMaximumSenderOwners = kMaximumSenders;
constexpr std::size_t kManagementConnectionHeadroom = 16;
constexpr std::size_t kMaximumConnections =
kMaximumSenders + kMaximumSenderOwners + kManagementConnectionHeadroom;
constexpr std::size_t kMaximumControlMessageBytes = 16U * 1024U;
constexpr std::size_t kMaximumDataMessageBytes = 64U * 1024U * 1024U + 64U;
constexpr std::size_t kMaximumInboundDataPayloadBytes =
128U * 1024U * 1024U;
constexpr std::size_t kMaximumQueuedWriteBytes = 256U * 1024U;
constexpr std::size_t kReadBufferBytes = 256U * 1024U;
constexpr std::uint64_t kHttpHeaderDeadlineMs = 1000;
constexpr std::uint64_t kControlHelloDeadlineMs = 1000;
constexpr std::uint64_t kPairingRequestDeadlineMs = 1000;
#if defined(SYNC_PAIRING_PROMPT_DEADLINE_MS)
static_assert(SYNC_PAIRING_PROMPT_DEADLINE_MS > 0);
constexpr std::uint64_t kPairingPromptDeadlineMs =
SYNC_PAIRING_PROMPT_DEADLINE_MS;
#else
constexpr std::uint64_t kPairingPromptDeadlineMs = 30'000;
#endif
#if defined(SYNC_PAIRING_COOLDOWN_MS)
static_assert(SYNC_PAIRING_COOLDOWN_MS > 0);
constexpr std::uint64_t kPairingCooldownMs = SYNC_PAIRING_COOLDOWN_MS;
#else
// Pairing is allowed to interrupt the performer, so one completed prompt
// suppresses every origin for a meaningful interval. Tests override this to
// keep the integration suite fast.
constexpr std::uint64_t kPairingCooldownMs = 30'000;
#endif
constexpr std::uint64_t kWebSocketCloseDeadlineMs = 750;
constexpr std::uint64_t kDataMessageDeadlineMs = 2'000;
constexpr std::uint64_t kDeadlineSweepIntervalMs = 50;
constexpr std::string_view kInboundBudgetReason =
"inbound_budget_exhausted";
constexpr std::string_view kIncompleteFrameReason =
"incomplete_frame_timeout";
class Server;
enum class ConnectionRole {
Http,
ControlUnauthenticated,
ControlAuthenticated,
Pairing,
Data,
};
enum class DeadlineKind {
None,
HttpHeader,
ControlHello,
PairingRequest,
PairingPrompt,
DataMessage,
WebSocketClose,
// A write after which the transport closes (an HTTP response): bounds how
// long a peer that stops reading can keep the slot.
FinalWrite,
};
enum class AuthorityState {
None,
AuthenticationPending,
PairingIssuePending,
};
struct Connection {
explicit Connection(Server &owner) : server(owner) {}
Server &server;
uv_tcp_t handle{};
std::size_t slot = kMaximumConnections;
ConnectionRole role = ConnectionRole::Http;
bool closing = false;
bool update_activity = false;
bool audio_pending = false;
bool audio_approved = false;
bool handle_closed = false;
std::unique_ptr<audio::Capture> audio_capture;
std::string audio_source_id;
bool transport_close_pending = false;
bool websocket_close_sent = false;
bool websocket_close_received = false;
bool websocket_close_write_completed = false;
bool force_close_after_websocket_write = false;
bool decoder_terminal = false;
DeadlineKind deadline_kind = DeadlineKind::None;
std::uint64_t deadline_ms = 0;
std::uint64_t data_message_generation = 0;
std::size_t pending_write_bytes = 0;
std::array<char, kReadBufferBytes> read_buffer{};
std::string http_buffer;
std::unique_ptr<websocket::ClientFrameDecoder> decoder;
std::optional<std::size_t> sender_slot;
NormalizedOrigin origin{};
std::uint64_t pairing_generation = 0;
bool pairing_message_received = false;
AuthorityState authority_state = AuthorityState::None;
std::uint64_t authority_generation = 0;
// SENDERS THIS CONNECTION OWNED THAT THE DAEMON REAPED UNDER IT.
//
// A sender is reaped when its DATA socket closes. The SDK's ordinary
// shutdown (SyncSender.close) drops the data socket FIRST and only then
// awaits closeSender, so the daemon routinely reaps a sender a heartbeat
// before its owner asks to close it — and answering sender_not_found there
// fails an ordinary stop() for a race the client cannot avoid.
//
// Remembering the ids lets closeSender stay idempotent for senders this
// connection genuinely owned, while a sender id that was never ours still
// answers sender_not_found. That distinction is worth keeping: blanket
// idempotency would report success for an id that never existed, which is a
// diagnostic an SDK author needs.
//
// A FIXED RING, not a growing set. A long-lived control connection may open
// and reap thousands of senders across a soak, and a per-connection
// container that grew with them would be a leak keyed on uptime. Four is
// ample: it covers the in-flight closes of a client shutting down, which is
// the only window in which the question is ever asked.
static constexpr std::size_t kReapedSenderMemory = 4;
std::array<std::string, kReapedSenderMemory> reaped_sender_ids{};
std::size_t reaped_sender_cursor = 0;
void remember_reaped_sender(std::string_view id) {
reaped_sender_ids[reaped_sender_cursor] = std::string(id);
reaped_sender_cursor = (reaped_sender_cursor + 1) % kReapedSenderMemory;
}
[[nodiscard]] bool reaped_sender_remembered(std::string_view id) const {
if (id.empty()) return false;
return std::any_of(reaped_sender_ids.begin(), reaped_sender_ids.end(),
[id](const std::string& seen) { return seen == id; });
}
};
struct Sender {
bool occupied = false;
std::string id;
std::string name;
std::string ticket;
Connection *owner = nullptr;
Connection *data = nullptr;
NormalizedOrigin origin{};
};
class ScopedStringCleanse {
public:
explicit ScopedStringCleanse(std::string &value) noexcept : value_(value) {}
~ScopedStringCleanse() {
if (!value_.empty())
OPENSSL_cleanse(value_.data(), value_.size());
}
ScopedStringCleanse(const ScopedStringCleanse &) = delete;
ScopedStringCleanse &operator=(const ScopedStringCleanse &) = delete;
private:
std::string &value_;
};
class ScopedByteCleanse {
public:
explicit ScopedByteCleanse(std::span<std::byte> value) noexcept
: value_(value) {}
~ScopedByteCleanse() {
if (!value_.empty())
OPENSSL_cleanse(value_.data(), value_.size());
}
ScopedByteCleanse(const ScopedByteCleanse &) = delete;
ScopedByteCleanse &operator=(const ScopedByteCleanse &) = delete;
private:
std::span<std::byte> value_;
};
class TestPublisher final : public FramePublisher {
public:
auto open_sender(std::string_view sender_id, std::string_view name) noexcept
-> bool override {
if (name == "__sync_test_reject_open__")
return false;
if (sender_id.empty() || sender_id.size() > 128 || name.empty() ||
name.size() > 64 || find(sender_id) != nullptr) {
return false;
}
for (Entry &entry : entries_) {
if (!entry.occupied) {
std::copy(sender_id.begin(), sender_id.end(), entry.id.begin());
std::copy(name.begin(), name.end(), entry.name.begin());
entry.id_length = sender_id.size();
entry.name_length = name.size();
entry.backpressure_once = name == "__sync_test_backpressure_once__";
entry.occupied = true;
return true;
}
}
return false;
}
void close_sender(std::string_view sender_id) noexcept override {
Entry* entry = find(sender_id);
if (entry != nullptr) *entry = Entry{};
}
auto publish(std::string_view sender_id, const protocol::FrameView& frame) noexcept
-> PublishResult override {
Entry* entry = find(sender_id);
if (entry == nullptr) return PublishResult::Failed;
if (entry->backpressure_once) {
entry->backpressure_once = false;
return PublishResult::Backpressured;
}
std::uint32_t checksum = 0x811c9dc5U;
const auto payload_to_hash =
frame.payload.size() <= 1048576
? frame.payload
: frame.payload.subspan(0, 65536);
for (const std::byte byte : payload_to_hash) {
checksum ^= std::to_integer<std::uint8_t>(byte);
checksum *= 0x01000193U;
}
entry->checksum = checksum;
return PublishResult::Accepted;
}
auto diagnostic_checksum(std::string_view sender_id) const noexcept
-> std::uint64_t override {
const Entry* entry = find(sender_id);
return entry == nullptr ? 0 : entry->checksum;
}
private:
struct Entry {
bool occupied = false;
std::size_t id_length = 0;
std::size_t name_length = 0;
std::array<char, 128> id{};
std::array<char, 64> name{};
std::uint32_t checksum = 0;
bool backpressure_once = false;
};
[[nodiscard]] Entry* find(std::string_view sender_id) noexcept {
if (sender_id.empty() || sender_id.size() > 128) return nullptr;
for (Entry& entry : entries_) {
if (entry.occupied && entry.id_length == sender_id.size() &&
std::string_view(entry.id.data(), entry.id_length) == sender_id) {
return &entry;
}
}
return nullptr;
}
[[nodiscard]] const Entry* find(std::string_view sender_id) const noexcept {
if (sender_id.empty() || sender_id.size() > 128) return nullptr;
for (const Entry& entry : entries_) {
if (entry.occupied && entry.id_length == sender_id.size() &&
std::string_view(entry.id.data(), entry.id_length) == sender_id) {
return &entry;
}
}
return nullptr;
}
std::array<Entry, kMaximumSenders> entries_{};
};
struct WriteRequest {
uv_write_t request{};
Connection *connection = nullptr;
std::vector<std::byte> bytes;
bool close_after = false;
bool websocket_close_write = false;
bool sensitive = false;
};
struct BasicHttpRequest {
std::string_view method;
std::string_view path;
std::string_view host;
std::optional<std::string_view> origin;
std::optional<std::string_view> requested_method;
bool requested_private_network = false;
};
std::string_view trim(std::string_view value) {
while (!value.empty() && (value.front() == ' ' || value.front() == '\t')) {
value.remove_prefix(1);
}
while (!value.empty() && (value.back() == ' ' || value.back() == '\t')) {
value.remove_suffix(1);
}
return value;
}
bool ascii_iequal(std::string_view left, std::string_view right) {
if (left.size() != right.size()) return false;
for (std::size_t index = 0; index < left.size(); ++index) {
const auto l = static_cast<unsigned char>(left[index]);
const auto r = static_cast<unsigned char>(right[index]);
if (std::tolower(l) != std::tolower(r)) return false;
}
return true;
}
bool valid_header_name(std::string_view name) {
if (name.empty()) return false;
for (const unsigned char byte : name) {
const bool alphanumeric = (byte >= 'A' && byte <= 'Z') ||
(byte >= 'a' && byte <= 'z') ||
(byte >= '0' && byte <= '9');
if (!(alphanumeric || byte == '!' || byte == '#' || byte == '$' || byte == '%' ||
byte == '&' || byte == '\'' || byte == '*' || byte == '+' || byte == '-' ||
byte == '.' || byte == '^' || byte == '_' || byte == '`' || byte == '|' ||
byte == '~')) {
return false;
}
}
return true;
}
bool valid_header_value(std::string_view value) {
for (const unsigned char byte : value) {
if ((byte < 0x20 && byte != '\t') || byte == 0x7f) return false;
}
return true;
}
std::optional<BasicHttpRequest> parse_basic_http(std::string_view bytes) {
if (bytes.size() > websocket::kMaximumHttpUpgradeBytes || bytes.size() < 4 ||
!bytes.ends_with("\r\n\r\n") ||
bytes.find("\r\n\r\n") != bytes.size() - 4) {
return std::nullopt;
}
for (std::size_t index = 0; index < bytes.size(); ++index) {
if (bytes[index] == '\n' && (index == 0 || bytes[index - 1] != '\r')) return std::nullopt;
if (bytes[index] == '\r' &&
(index + 1 >= bytes.size() || bytes[index + 1] != '\n')) {
return std::nullopt;
}
}
const std::size_t first_end = bytes.find("\r\n");
const std::string_view request_line = bytes.substr(0, first_end);
const std::size_t first_space = request_line.find(' ');
const std::size_t second_space = first_space == std::string_view::npos
? std::string_view::npos
: request_line.find(' ', first_space + 1);
if (first_space == std::string_view::npos || second_space == std::string_view::npos ||
request_line.find(' ', second_space + 1) != std::string_view::npos ||
request_line.substr(second_space + 1) != "HTTP/1.1") {
return std::nullopt;
}
for (const unsigned char byte : request_line) {
if (byte < 0x20 || byte == 0x7f) return std::nullopt;
}
BasicHttpRequest request{
.method = request_line.substr(0, first_space),
.path = request_line.substr(first_space + 1, second_space - first_space - 1),
.host = {},
.origin = std::nullopt,
.requested_method = std::nullopt,
.requested_private_network = false,
};
if (request.method.empty() || request.path.empty()) return std::nullopt;
bool saw_host = false;
bool saw_origin = false;
bool saw_requested_method = false;
bool saw_requested_private_network = false;
std::size_t position = first_end + 2;
while (position < bytes.size() - 2) {
const std::size_t end = bytes.find("\r\n", position);
if (end == std::string_view::npos) return std::nullopt;
const std::string_view line = bytes.substr(position, end - position);
position = end + 2;
if (line.empty()) break;
const std::size_t colon = line.find(':');
if (colon == std::string_view::npos) return std::nullopt;
const std::string_view name = line.substr(0, colon);
const std::string_view value = trim(line.substr(colon + 1));
if (!valid_header_name(name) || !valid_header_value(value)) return std::nullopt;
if (ascii_iequal(name, "Host")) {
if (saw_host || value.empty()) return std::nullopt;
saw_host = true;
request.host = value;
} else if (ascii_iequal(name, "Origin")) {
if (saw_origin || value.empty()) return std::nullopt;
saw_origin = true;
request.origin = value;
} else if (ascii_iequal(name, "Access-Control-Request-Method")) {
if (saw_requested_method || value.empty()) return std::nullopt;
saw_requested_method = true;
request.requested_method = value;
} else if (ascii_iequal(name, "Access-Control-Request-Private-Network")) {
if (saw_requested_private_network || value != "true") return std::nullopt;
saw_requested_private_network = true;
request.requested_private_network = true;
}
}
return saw_host ? std::optional<BasicHttpRequest>(request) : std::nullopt;
}
std::string random_hex(std::size_t byte_count) {
if (byte_count == 0 || byte_count > 32) return {};
std::array<unsigned char, 32> bytes{};
if (RAND_bytes(bytes.data(), static_cast<int>(byte_count)) != 1) return {};
static constexpr char kHex[] = "0123456789abcdef";
std::string result(byte_count * 2, '0');
for (std::size_t index = 0; index < byte_count; ++index) {
result[index * 2] = kHex[bytes[index] >> 4U];
result[index * 2 + 1] = kHex[bytes[index] & 0x0fU];
}
return result;
}
std::span<const std::byte> as_bytes(std::string_view value) {
return {reinterpret_cast<const std::byte*>(value.data()), value.size()};
}
std::array<std::byte, 2> close_code(std::uint16_t code) {
return {static_cast<std::byte>((code >> 8U) & 0xffU),
static_cast<std::byte>(code & 0xffU)};
}
std::vector<std::byte> close_status_payload(std::uint16_t code,
std::string_view reason) {
constexpr std::size_t kMaximumCloseReasonBytes = 123;
if (reason.size() > kMaximumCloseReasonBytes) return {};
const auto encoded_code = close_code(code);
std::vector<std::byte> payload;
payload.reserve(encoded_code.size() + reason.size());
payload.insert(payload.end(), encoded_code.begin(), encoded_code.end());
const auto reason_bytes = as_bytes(reason);
payload.insert(payload.end(), reason_bytes.begin(), reason_bytes.end());
return payload;
}
class Server {
public:
Server(const ServerOptions& options, FramePublisher& publisher)
: options_(options),
data_payload_memory_(kMaximumInboundDataPayloadBytes),
publisher_(publisher),
receiver_(publisher) {
if (options_.pairing_authority != nullptr) {
authority_worker_ =
std::make_unique<pairing::AuthorityWorker>(*options_.pairing_authority);
}
for (const ProviderCapability& provider : provider_capabilities()) {
if (provider.available && provider.selected &&
provider.direction == ProviderDirection::Send) {
can_send_ = true;
}
}
}
int run() {
if (!initialize()) {
close_initialized_handles();
if (loop_initialized_) {
uv_run(&loop_, UV_RUN_DEFAULT);
uv_loop_close(&loop_);
}
return 1;
}
// `loopback` reports the stacks actually bound so a host that degraded to
// IPv4 says so rather than looking identical to a dual-stack daemon.
std::cout << "{\"type\":\"ready\",\"port\":" << port_
<< ",\"protocolVersions\":[1],\"loopback\":[\"127.0.0.1\""
<< (ipv6_listening_ ? ",\"::1\"" : "") << "],\"instanceId\":\""
<< instance_id_ << "\"}" << std::endl;
uv_run(&loop_, UV_RUN_DEFAULT);
const int close_result = uv_loop_close(&loop_);
if (close_result != 0) {
std::cerr << "syncd: event loop did not close cleanly: " << uv_strerror(close_result)
<< '\n';
return 1;
}
return fatal_exit_ ? 1 : 0;
}
void accept_connection(uv_stream_t* listener) {
if (stopping_) return;
std::size_t slot = kMaximumConnections;
for (std::size_t index = 0; index < connections_.size(); ++index) {
if (connections_[index] == nullptr) {
slot = index;
break;
}
}
auto* connection = new (std::nothrow) Connection(*this);
if (connection == nullptr) return;
if (uv_tcp_init(&loop_, &connection->handle) != 0) {
delete connection;
return;
}
connection->handle.data = connection;
if (uv_accept(listener, reinterpret_cast<uv_stream_t*>(&connection->handle)) != 0) {
uv_close(reinterpret_cast<uv_handle_t*>(&connection->handle), [](uv_handle_t* handle) {
delete static_cast<Connection*>(handle->data);
});
return;
}
if (slot == kMaximumConnections) {
uv_close(reinterpret_cast<uv_handle_t*>(&connection->handle), [](uv_handle_t* handle) {
delete static_cast<Connection*>(handle->data);
});
return;
}
connection->slot = slot;
connections_[slot] = connection;
set_deadline(*connection, DeadlineKind::HttpHeader, kHttpHeaderDeadlineMs);
uv_tcp_nodelay(&connection->handle, 1);
int rcv_buf = 4 * 1024 * 1024;
uv_recv_buffer_size(reinterpret_cast<uv_handle_t*>(&connection->handle), &rcv_buf);
const int read_result = uv_read_start(
reinterpret_cast<uv_stream_t*>(&connection->handle), allocate_read_buffer, on_read);
if (read_result != 0) close_connection(*connection);
}
void consume(Connection& connection, std::span<const std::byte> bytes) {
if (connection.closing || connection.transport_close_pending) return;
if (connection.role != ConnectionRole::Http) {
consume_websocket(connection, bytes);
return;
}
connection.http_buffer.append(reinterpret_cast<const char*>(bytes.data()), bytes.size());
const std::size_t header_end = connection.http_buffer.find("\r\n\r\n");
// Only the request head counts against the header budget. Bytes past the
// terminator belong to the WebSocket stream a client may pipeline behind
// its upgrade, and rejecting those as oversized headers drops valid
// connections.
const std::size_t header_bytes =
header_end == std::string::npos ? connection.http_buffer.size() : header_end + 4;
if (header_bytes > websocket::kMaximumHttpUpgradeBytes) {
connection.http_buffer.clear();
send_http(connection, 431, "Request Header Fields Too Large",
"{\"error\":\"headers_too_large\"}");
return;
}
if (header_end == std::string::npos) return;
std::vector<std::byte> remainder;
remainder.reserve(connection.http_buffer.size() - header_bytes);
const auto* first = reinterpret_cast<const std::byte*>(connection.http_buffer.data());
remainder.insert(remainder.end(), first + header_bytes, first + connection.http_buffer.size());
const std::string header = connection.http_buffer.substr(0, header_bytes);
connection.http_buffer.clear();
handle_http(connection, header);
if (!connection.closing && !connection.transport_close_pending &&
connection.role != ConnectionRole::Http && !remainder.empty()) {
consume_websocket(connection, remainder);
}
}
void close_connection(Connection &connection) {
if (connection.closing)
return;
connection.closing = true;
connection.deadline_kind = DeadlineKind::None;
connection.deadline_ms = 0;
invalidate_authority(connection);
uv_read_stop(reinterpret_cast<uv_stream_t *>(&connection.handle));
if (connection.role == ConnectionRole::Pairing &&
connection.pairing_generation != 0 &&
connection.pairing_generation == active_pairing_generation_) {
if (options_.pairing_prompt != nullptr) {
options_.pairing_prompt->cancel(active_pairing_generation_);
}
active_pairing_generation_ = 0;
connection.pairing_generation = 0;
apply_pairing_cooldown(connection.origin, uv_now(&loop_));
}
if (connection.role == ConnectionRole::ControlAuthenticated ||
connection.role == ConnectionRole::ControlUnauthenticated) {
remove_owned_senders(connection, false);
} else if (connection.role == ConnectionRole::Data && connection.sender_slot.has_value()) {
Sender& sender = senders_[*connection.sender_slot];
if (sender.occupied && sender.data == &connection) {
// REAP THE SENDER. Nulling the pointer left it occupied and still
// registered with every publisher, and the sender could never be used
// again anyway: the ticket is cleared the moment a data socket
// attaches, so no second data socket can ever bind to this slot.
//
// Leaving it registered is not inert. The camera publisher drives from
// the occupied entry with the LOWEST opened_at, and a non-driving
// sender's frames are accepted and dropped by design. So a stranded
// dead entry keeps driving forever, and the REPLACEMENT sender — which
// opens later and therefore sorts after it — publishes into a
// publisher that ignores it. Every frame returns Accepted and is
// discarded, the sender's own counters climb normally, and the
// consumer's picture freezes permanently while everything reports
// healthy.
//
// Measured on an Apple Silicon Mac: a transport close, a replacement sender three
// seconds later, five seconds of the old delivery draining, then 954
// seconds frozen on one frame with the new sender reporting 24.6 fps
// and its counter climbing 28 -> 102 -> 163.
//
// The reap was previously reachable only from a CONTROL teardown or an
// explicit closeSender message — and the SDK fires that message
// unawaited with its errors swallowed, so the daemon's only route to
// learning its sender had gone was one it could not rely on. It now
// learns from the socket it owns.
//
// graceful_data_close is false: this connection is already closing,
// remove_sender's own guard skips it, and there is nothing to close
// gracefully.
remove_sender(*connection.sender_slot, false);
}
}
uv_close(reinterpret_cast<uv_handle_t*>(&connection.handle), [](uv_handle_t* handle) {
auto* closed = static_cast<Connection*>(handle->data);
closed->handle_closed = true;
if (!closed->audio_pending) closed->server.connection_closed(*closed);
});
if (!connection.audio_pending && connection.audio_capture)
audio_request(connection, control::MessageType::CloseAudioSource, {}, true);
}
void connection_closed(Connection& connection) {
if (connection.slot < connections_.size() && connections_[connection.slot] == &connection) {
// No job is pending here: joining this connection's idle worker never
// waits for a driver operation belonging to another connection.
audio_workers_[connection.slot].reset();
connections_[connection.slot] = nullptr;
}
if (connection.update_activity && options_.update_coordinator != nullptr) {
options_.update_coordinator->end_activity(uv_hrtime() / 1000000);
}
delete &connection;
}
void begin_shutdown() {
if (stopping_) return;
stopping_ = true;
if (active_pairing_generation_ != 0 && options_.pairing_prompt != nullptr) {
options_.pairing_prompt->cancel(active_pairing_generation_);
active_pairing_generation_ = 0;
}
close_initialized_handles();
const auto snapshot = connections_;
for (Connection* connection : snapshot) {
if (connection != nullptr) close_connection(*connection);
}
close_idle_audio_async();
}
void begin_fatal_shutdown(const ProviderFailure& failure) noexcept {
if (stopping_ || fatal_exit_) return;
fatal_exit_ = true;
std::cerr << "syncd: fatal provider failure: "
<< provider_failure_name(failure.kind)
<< " status=" << failure.native_status
<< " error=" << failure.native_error_code << '\n';
begin_shutdown();
}
private:
static void on_listener_connection(uv_stream_t* listener, int status) {
if (status < 0) return;
static_cast<Server*>(listener->data)->accept_connection(listener);
}
static void on_signal(uv_signal_t* signal, int) {
static_cast<Server*>(signal->data)->begin_shutdown();
}
static void on_authority_ready(uv_async_t* handle) {
auto* server = static_cast<Server*>(handle->data);
server->poll_pairing_prompt();
server->poll_authority_results();
}
static void on_deadline_sweep(uv_timer_t* timer) {
auto *server = static_cast<Server *>(timer->data);
if (server->options_.platform_event_pump != nullptr) {
server->options_.platform_event_pump(
server->options_.platform_event_pump_context);
}
server->sweep_deadlines();
}
static void allocate_read_buffer(uv_handle_t* handle,
std::size_t,
uv_buf_t* buffer) {
auto* connection = static_cast<Connection*>(handle->data);
*buffer = uv_buf_init(connection->read_buffer.data(),
static_cast<unsigned int>(connection->read_buffer.size()));
}
static void on_read(uv_stream_t* stream, ssize_t count, const uv_buf_t* buffer) {
auto* connection = static_cast<Connection*>(stream->data);
if (count > 0 && buffer->base != nullptr) {
try {
connection->server.consume(
*connection,
{reinterpret_cast<const std::byte*>(buffer->base), static_cast<std::size_t>(count)});
} catch (const std::exception&) {
connection->server.close_connection(*connection);
}
} else if (count < 0) {
connection->server.close_connection(*connection);
}
}
static void on_write(uv_write_t *request, int status) {
auto *write = static_cast<WriteRequest *>(request->data);
Connection *connection = write->connection;
if (connection->pending_write_bytes >= write->bytes.size()) {
connection->pending_write_bytes -= write->bytes.size();
} else {
connection->pending_write_bytes = 0;
}
const bool close_after = write->close_after;
const bool websocket_close_write = write->websocket_close_write;
if (write->sensitive && !write->bytes.empty()) {
OPENSSL_cleanse(write->bytes.data(), write->bytes.size());
}
delete write;
if (status < 0) {
connection->server.close_connection(*connection);
return;
}
if (websocket_close_write) {
connection->websocket_close_write_completed = true;
if (connection->websocket_close_received ||
connection->force_close_after_websocket_write) {
connection->server.close_connection(*connection);
return;
}
}
if (close_after)
connection->server.close_connection(*connection);
}
bool initialize() {
if (uv_loop_init(&loop_) != 0) {
std::cerr << "syncd: failed to initialize event loop\n";
return false;
}
loop_initialized_ = true;
instance_id_ = random_hex(16);
if (instance_id_.empty()) {
std::cerr << "syncd: failed to generate instance identifier\n";
return false;
}
welcome_body_ = control::encode_welcome(
1, kProductVersion, instance_id_, provider_capabilities());
health_body_ = control::encode_health(
kProductVersion, instance_id_, provider_capabilities());
sockaddr_in address4{};
if (uv_ip4_addr("127.0.0.1", options_.port, &address4) != 0 ||
uv_tcp_init(&loop_, &listener4_) != 0) {
std::cerr << "syncd: failed to initialize IPv4 listener\n";
return false;
}
listener4_initialized_ = true;
listener4_.data = this;
int result = uv_tcp_bind(&listener4_, reinterpret_cast<const sockaddr*>(&address4), 0);
if (result != 0) {
std::cerr << "syncd: failed to bind IPv4 loopback: " << uv_strerror(result) << '\n';
return false;
}
sockaddr_storage selected{};
int selected_length = sizeof(selected);
result = uv_tcp_getsockname(&listener4_, reinterpret_cast<sockaddr*>(&selected), &selected_length);
if (result != 0 || selected.ss_family != AF_INET) {
std::cerr << "syncd: failed to read selected loopback port\n";
return false;
}
port_ = ntohs(reinterpret_cast<const sockaddr_in*>(&selected)->sin_port);
// IPv4 loopback is the contract. IPv6 loopback is served when the host
// offers it, but a host with IPv6 disabled must still get a working daemon
// rather than a process that refuses to start.
sockaddr_in6 address6{};
bool ipv6_ready = uv_ip6_addr("::1", port_, &address6) == 0 &&
uv_tcp_init(&loop_, &listener6_) == 0;
if (ipv6_ready) {
listener6_initialized_ = true;
listener6_.data = this;
result =
uv_tcp_bind(&listener6_, reinterpret_cast<const sockaddr*>(&address6), UV_TCP_IPV6ONLY);
if (result != 0) {
std::cerr << "syncd: IPv6 loopback unavailable, serving IPv4 only: "
<< uv_strerror(result) << '\n';
ipv6_ready = false;
}
} else {
std::cerr << "syncd: IPv6 loopback unavailable, serving IPv4 only\n";
}
result = uv_listen(reinterpret_cast<uv_stream_t*>(&listener4_), 64, on_listener_connection);
if (result != 0) {
std::cerr << "syncd: failed to listen on IPv4 loopback: " << uv_strerror(result) << '\n';
return false;
}
if (ipv6_ready) {
result = uv_listen(reinterpret_cast<uv_stream_t*>(&listener6_), 64, on_listener_connection);
if (result != 0) {
std::cerr << "syncd: IPv6 loopback unavailable, serving IPv4 only: "
<< uv_strerror(result) << '\n';
ipv6_ready = false;
}
}
ipv6_listening_ = ipv6_ready;
if (uv_signal_init(&loop_, &signal_int_) != 0) return false;
signal_int_initialized_ = true;
signal_int_.data = this;
if (uv_signal_start(&signal_int_, on_signal, SIGINT) != 0) return false;
if (uv_signal_init(&loop_, &signal_term_) != 0) return false;
signal_term_initialized_ = true;
signal_term_.data = this;
// The second stop signal differs by platform, and getting this wrong is
// silent: uv_signal_start accepts SIGTERM on Windows and returns success,
// but nothing ever delivers it there -- a CRT raise(SIGTERM) terminates
// the process outright instead of reaching the loop. The Windows
// companion stops its helper with CTRL_BREAK_EVENT, which the OS delivers
// as SIGBREAK, so that is the signal this has to watch for shutdown to be
// graceful rather than a kill.
#if defined(_WIN32)
constexpr int kSecondStopSignal = SIGBREAK;
#else
constexpr int kSecondStopSignal = SIGTERM;
#endif
if (uv_signal_start(&signal_term_, on_signal, kSecondStopSignal) != 0) return false;
// Authority results are produced on the worker thread. Waking the loop the
// moment one lands keeps hello-to-welcome off the sweep interval; the
// sweep remains as the deadline and prompt-polling path.
if (uv_async_init(&loop_, &authority_async_, on_authority_ready) != 0) return false;
authority_async_initialized_ = true;
authority_async_.data = this;
uv_unref(reinterpret_cast<uv_handle_t*>(&authority_async_));
if (authority_worker_ != nullptr) {
authority_worker_->set_result_notifier(
[](void* context) noexcept {
uv_async_send(&static_cast<Server*>(context)->authority_async_);
},
this);
}
if (uv_async_init(&loop_, &audio_async_, [](uv_async_t *handle) {
static_cast<Server *>(handle->data)->poll_audio_results();
}) != 0) return false;
audio_async_initialized_ = true;
audio_async_.data = this;
uv_unref(reinterpret_cast<uv_handle_t *>(&audio_async_));
if (uv_timer_init(&loop_, &deadline_timer_) != 0) return false;
deadline_timer_initialized_ = true;
deadline_timer_.data = this;
if (uv_timer_start(&deadline_timer_,
on_deadline_sweep,
kDeadlineSweepIntervalMs,
kDeadlineSweepIntervalMs) != 0) {
return false;
}
// Last, so every handle the render path shares the loop with exists. A
// render supervisor that cannot start costs the render sender only:
// browser senders are served either way.
if (options_.render != nullptr) {
render_supervisor_ =
std::make_unique<render::RenderSupervisor>(&loop_, publisher_, *options_.render);
if (!render_supervisor_->start()) {
std::cerr << "syncd: render supervisor failed to start\n";
render_supervisor_->stop();
}
}
return true;
}
void close_initialized_handles() {
// Retire the notifier before the async handle goes away; the worker
// publishes results under its own lock, so clearing here cannot race a
// uv_async_send already on its way to a closing handle.
if (authority_worker_ != nullptr) {
authority_worker_->set_result_notifier(nullptr, nullptr);
}
auto close_handle = [](uv_handle_t* handle) {
if (!uv_is_closing(handle)) uv_close(handle, nullptr);
};
// During shutdown, audio cleanup keeps its notifier alive until every
// capture has been destroyed. Initialization failure has no audio work.
if (audio_async_initialized_ && !stopping_)
close_handle(reinterpret_cast<uv_handle_t *>(&audio_async_));
if (authority_async_initialized_) {
close_handle(reinterpret_cast<uv_handle_t*>(&authority_async_));
}
if (listener4_initialized_) close_handle(reinterpret_cast<uv_handle_t*>(&listener4_));
if (listener6_initialized_) close_handle(reinterpret_cast<uv_handle_t*>(&listener6_));
if (signal_int_initialized_) {
uv_signal_stop(&signal_int_);
close_handle(reinterpret_cast<uv_handle_t*>(&signal_int_));
}
if (signal_term_initialized_) {
uv_signal_stop(&signal_term_);
close_handle(reinterpret_cast<uv_handle_t*>(&signal_term_));
}
if (deadline_timer_initialized_) {
uv_timer_stop(&deadline_timer_);
close_handle(reinterpret_cast<uv_handle_t*>(&deadline_timer_));
}
// Closes the render sender, asks the helper to exit, and closes the
// supervisor's handles, which the shutdown loop then runs to completion.
if (render_supervisor_ != nullptr) render_supervisor_->stop();
}
bool valid_host(std::string_view host) const {
const std::string port = std::to_string(port_);
return host == "127.0.0.1:" + port || host == "[::1]:" + port;
}
[[nodiscard]] auto provider_capabilities() const noexcept
-> std::span<const ProviderCapability> {
return {options_.providers.data(), options_.provider_count};
}
[[nodiscard]] std::size_t active_sender_count() const noexcept {
std::size_t count = 0;
for (const Sender& sender : senders_) {
if (sender.occupied) ++count;
}
return count;
}
void set_deadline(Connection &connection, DeadlineKind kind,
std::uint64_t duration_ms) noexcept {
connection.deadline_kind = kind;
connection.deadline_ms = uv_now(&loop_) + duration_ms;
}
void clear_deadline(Connection &connection) noexcept {
connection.deadline_kind = DeadlineKind::None;
connection.deadline_ms = 0;
}
void sweep_deadlines() noexcept {
const std::uint64_t now = uv_now(&loop_);
if (poll_provider_failure(now)) return;
for (Connection *connection : connections_) {
if (connection == nullptr || connection->closing ||
connection->deadline_kind == DeadlineKind::None ||
connection->deadline_ms > now) {
continue;
}
const DeadlineKind expired = connection->deadline_kind;
clear_deadline(*connection);
if (expired == DeadlineKind::HttpHeader ||
expired == DeadlineKind::WebSocketClose ||
expired == DeadlineKind::FinalWrite) {