-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathNet2.actor.cpp
2357 lines (2039 loc) · 76.6 KB
/
Net2.actor.cpp
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
/*
* Net2.actor.cpp
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2013-2024 Apple Inc. and the FoundationDB project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "boost/asio/buffer.hpp"
#include "boost/asio/ip/address.hpp"
#include "boost/system/system_error.hpp"
#include "flow/Arena.h"
#include "flow/Platform.h"
#include "flow/Trace.h"
#include "flow/swift.h"
#include "flow/swift_concurrency_hooks.h"
#include <algorithm>
#include <memory>
#include <string_view>
#ifndef BOOST_SYSTEM_NO_LIB
#define BOOST_SYSTEM_NO_LIB
#endif
#ifndef BOOST_DATE_TIME_NO_LIB
#define BOOST_DATE_TIME_NO_LIB
#endif
#ifndef BOOST_REGEX_NO_LIB
#define BOOST_REGEX_NO_LIB
#endif
#include <boost/asio.hpp>
#include "boost/asio/ssl.hpp"
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/range.hpp>
#include <boost/algorithm/string/join.hpp>
#include "flow/network.h"
#include "flow/IThreadPool.h"
#include "flow/IAsyncFile.h"
#include "flow/ActorCollection.h"
#include "flow/TaskQueue.h"
#include "flow/ThreadHelper.actor.h"
#include "flow/ChaosMetrics.h"
#include "flow/TDMetric.actor.h"
#include "flow/AsioReactor.h"
#include "flow/Profiler.h"
#include "flow/ProtocolVersion.h"
#include "flow/SendBufferIterator.h"
#include "flow/TLSConfig.actor.h"
#include "flow/WatchFile.actor.h"
#include "flow/genericactors.actor.h"
#include "flow/Util.h"
#include "flow/UnitTest.h"
#include "flow/ScopeExit.h"
#include "flow/IUDPSocket.h"
#include "flow/IConnection.h"
#ifdef ADDRESS_SANITIZER
#include <sanitizer/lsan_interface.h>
#endif
#ifdef WIN32
#include <mmsystem.h>
#endif
#include "flow/actorcompiler.h" // This must be the last #include.
// Defined to track the stack limit
extern "C" intptr_t g_stackYieldLimit;
intptr_t g_stackYieldLimit = 0;
using namespace boost::asio::ip;
#if defined(__linux__) || defined(__FreeBSD__)
#include <execinfo.h>
std::atomic<int64_t> net2RunLoopIterations(0);
std::atomic<int64_t> net2RunLoopSleeps(0);
volatile size_t net2backtraces_max = 10000;
volatile void** volatile net2backtraces = nullptr;
volatile size_t net2backtraces_offset = 0;
volatile bool net2backtraces_overflow = false;
volatile int net2backtraces_count = 0;
volatile void** other_backtraces = nullptr;
sigset_t sigprof_set;
void initProfiling() {
net2backtraces = new volatile void*[net2backtraces_max];
other_backtraces = new volatile void*[net2backtraces_max];
// According to folk wisdom, calling this once before setting up the signal handler makes
// it async signal safe in practice :-/
backtrace(const_cast<void**>(other_backtraces), net2backtraces_max);
sigemptyset(&sigprof_set);
sigaddset(&sigprof_set, SIGPROF);
}
#endif
DESCR struct SlowTask {
int64_t clocks; // clocks
int64_t duration; // ns
int64_t priority; // priority level
int64_t numYields; // count
};
namespace N2 { // No indent, it's the whole file
class Peer;
class Connection;
// Outlives main
Net2* g_net2 = nullptr;
thread_local INetwork* thread_network = nullptr;
class Net2 final : public INetwork, public INetworkConnections {
private:
void updateStarvationTracker(struct NetworkMetrics::PriorityStats& binStats,
TaskPriority priority,
TaskPriority lastPriority,
double now);
public:
Net2(const TLSConfig& tlsConfig, bool useThreadPool, bool useMetrics);
void initTLS(ETLSInitState targetState) override;
void run() override;
void initMetrics() override;
// INetworkConnections interface
Future<Reference<IConnection>> connect(NetworkAddress toAddr, tcp::socket* existingSocket = nullptr) override;
Future<Reference<IConnection>> connectExternal(NetworkAddress toAddr) override;
Future<Reference<IUDPSocket>> createUDPSocket(NetworkAddress toAddr) override;
Future<Reference<IUDPSocket>> createUDPSocket(bool isV6) override;
// The mock DNS methods should only be used in simulation.
void addMockTCPEndpoint(const std::string& host,
const std::string& service,
const std::vector<NetworkAddress>& addresses) override {
throw operation_failed();
}
// The mock DNS methods should only be used in simulation.
void removeMockTCPEndpoint(const std::string& host, const std::string& service) override {
throw operation_failed();
}
void parseMockDNSFromString(const std::string& s) override { throw operation_failed(); }
std::string convertMockDNSToString() override { throw operation_failed(); }
Future<std::vector<NetworkAddress>> resolveTCPEndpoint(const std::string& host,
const std::string& service) override;
Future<std::vector<NetworkAddress>> resolveTCPEndpointWithDNSCache(const std::string& host,
const std::string& service) override;
std::vector<NetworkAddress> resolveTCPEndpointBlocking(const std::string& host,
const std::string& service) override;
std::vector<NetworkAddress> resolveTCPEndpointBlockingWithDNSCache(const std::string& host,
const std::string& service) override;
Reference<IListener> listen(NetworkAddress localAddr) override;
// INetwork interface
double now() const override { return currentTime; };
double timer() override { return ::timer(); };
double timer_monotonic() override { return ::timer_monotonic(); };
Future<Void> delay(double seconds, TaskPriority taskId) override;
Future<Void> orderedDelay(double seconds, TaskPriority taskId) override;
void _swiftEnqueue(void* task) override;
Future<class Void> yield(TaskPriority taskID) override;
bool check_yield(TaskPriority taskId) override;
TaskPriority getCurrentTask() const override { return currentTaskID; }
void setCurrentTask(TaskPriority taskID) override {
currentTaskID = taskID;
priorityMetric = (int64_t)taskID;
}
void onMainThread(Promise<Void>&& signal, TaskPriority taskID) override;
bool isOnMainThread() const override { return thread_network == this; }
void stop() override {
if (thread_network == this)
stopImmediately();
else
onMainThreadVoid([this] { this->stopImmediately(); });
}
void addStopCallback(std::function<void()> fn) override {
if (thread_network == this)
stopCallbacks.emplace_back(std::move(fn));
else
onMainThreadVoid([this, fn] { this->stopCallbacks.emplace_back(std::move(fn)); });
}
bool isSimulated() const override { return false; }
THREAD_HANDLE startThread(THREAD_FUNC_RETURN (*func)(void*), void* arg, int stackSize, const char* name) override;
void getDiskBytes(std::string const& directory, int64_t& free, int64_t& total) override;
bool isAddressOnThisHost(NetworkAddress const& addr) const override;
void updateNow() { currentTime = timer_monotonic(); }
flowGlobalType global(int id) const override { return (globals.size() > id) ? globals[id] : nullptr; }
void setGlobal(size_t id, flowGlobalType v) override {
ASSERT(id < globals.size());
globals[id] = v;
}
ProtocolVersion protocolVersion() const override { return currentProtocolVersion(); }
std::vector<flowGlobalType> globals;
const TLSConfig& getTLSConfig() const override { return tlsConfig; }
bool checkRunnable() override;
#ifdef ENABLE_SAMPLING
ActorLineageSet& getActorLineageSet() override;
#endif
bool useThreadPool;
// private:
ASIOReactor reactor;
AsyncVar<Reference<ReferencedObject<boost::asio::ssl::context>>> sslContextVar;
Reference<IThreadPool> sslHandshakerPool;
int sslHandshakerThreadsStarted;
int sslPoolHandshakesInProgress;
TLSConfig tlsConfig;
Reference<TLSPolicy> activeTlsPolicy;
Future<Void> backgroundCertRefresh;
ETLSInitState tlsInitializedState;
INetworkConnections* network; // initially this, but can be changed
int64_t tscBegin, tscEnd;
double taskBegin;
TaskPriority currentTaskID;
TDMetricCollection tdmetrics;
MetricCollection metrics;
ChaosMetrics chaosMetrics;
// we read now() from a different thread. On Intel, reading a double is atomic anyways, but on other platforms it's
// not. For portability this should be atomic
std::atomic<double> currentTime;
// May be accessed off the network thread, e.g. by onMainThread
std::atomic<bool> stopped;
mutable std::map<IPAddress, bool> addressOnHostCache;
#ifdef ENABLE_SAMPLING
ActorLineageSet actorLineageSet;
#endif
std::atomic<bool> started;
uint64_t numYields;
NetworkMetrics::PriorityStats* lastPriorityStats;
struct PromiseTask final : public FastAllocated<PromiseTask> {
Promise<Void> promise;
swift::Job* _Nullable swiftJob = nullptr;
PromiseTask() {}
explicit PromiseTask(Promise<Void>&& promise) noexcept : promise(std::move(promise)) {}
explicit PromiseTask(swift::Job* swiftJob) : swiftJob(swiftJob) {}
void operator()() {
#ifdef WITH_SWIFT
if (auto job = swiftJob) {
swift_job_run(job, ExecutorRef::generic());
} else {
promise.send(Void());
}
#else
promise.send(Void());
#endif
delete this;
}
};
TaskQueue<PromiseTask> taskQueue;
void checkForSlowTask(int64_t tscBegin, int64_t tscEnd, double duration, TaskPriority priority);
bool check_yield(TaskPriority taskId, int64_t tscNow);
void trackAtPriority(TaskPriority priority, double now);
void stopImmediately() {
#ifdef ADDRESS_SANITIZER
// Do leak check before intentionally leaking a bunch of memory
__lsan_do_leak_check();
#endif
stopped = true;
taskQueue.clear();
}
Future<Void> timeOffsetLogger;
Future<Void> logTimeOffset();
Int64MetricHandle bytesReceived;
Int64MetricHandle udpBytesReceived;
Int64MetricHandle countWriteProbes;
Int64MetricHandle countReadProbes;
Int64MetricHandle countReads;
Int64MetricHandle countUDPReads;
Int64MetricHandle countWouldBlock;
Int64MetricHandle countWrites;
Int64MetricHandle countUDPWrites;
Int64MetricHandle countRunLoop;
Int64MetricHandle countTasks;
Int64MetricHandle countYields;
Int64MetricHandle countYieldBigStack;
Int64MetricHandle countYieldCalls;
Int64MetricHandle countYieldCallsTrue;
Int64MetricHandle countASIOEvents;
Int64MetricHandle countRunLoopProfilingSignals;
Int64MetricHandle countTLSPolicyFailures;
Int64MetricHandle priorityMetric;
DoubleMetricHandle countLaunchTime;
DoubleMetricHandle countReactTime;
BoolMetricHandle awakeMetric;
EventMetricHandle<SlowTask> slowTaskMetric;
std::vector<std::string> blobCredentialFiles;
std::vector<std::function<void()>> stopCallbacks;
};
static boost::asio::ip::address tcpAddress(IPAddress const& n) {
if (n.isV6()) {
return boost::asio::ip::address_v6(n.toV6());
} else {
return boost::asio::ip::address_v4(n.toV4());
}
}
static IPAddress toIPAddress(boost::asio::ip::address const& addr) {
if (addr.is_v4()) {
return IPAddress(addr.to_v4().to_uint());
} else {
return IPAddress(addr.to_v6().to_bytes());
}
}
static tcp::endpoint tcpEndpoint(NetworkAddress const& n) {
return tcp::endpoint(tcpAddress(n.ip), n.port);
}
static udp::endpoint udpEndpoint(NetworkAddress const& n) {
return udp::endpoint(tcpAddress(n.ip), n.port);
}
class BindPromise {
Promise<Void> p;
std::variant<const char*, AuditedEvent> errContext;
UID errID;
NetworkAddress peerAddr;
public:
BindPromise(const char* errContext, UID errID) : errContext(errContext), errID(errID) {}
BindPromise(AuditedEvent auditedEvent, UID errID) : errContext(auditedEvent), errID(errID) {}
BindPromise(BindPromise const& r) : p(r.p), errContext(r.errContext), errID(r.errID), peerAddr(r.peerAddr) {}
BindPromise(BindPromise&& r) noexcept
: p(std::move(r.p)), errContext(r.errContext), errID(r.errID), peerAddr(r.peerAddr) {}
Future<Void> getFuture() const { return p.getFuture(); }
NetworkAddress getPeerAddr() const { return peerAddr; }
void setPeerAddr(const NetworkAddress& addr) { peerAddr = addr; }
void operator()(const boost::system::error_code& error, size_t bytesWritten = 0) {
try {
if (error) {
// Log the error...
{
std::optional<TraceEvent> traceEvent;
if (std::holds_alternative<AuditedEvent>(errContext))
traceEvent.emplace(SevWarn, std::get<AuditedEvent>(errContext), errID);
else
traceEvent.emplace(SevWarn, std::get<const char*>(errContext), errID);
TraceEvent& evt = *traceEvent;
evt.suppressFor(1.0).detail("ErrorCode", error.value()).detail("Message", error.message());
// There is no function in OpenSSL to use to check if an error code is from OpenSSL,
// but all OpenSSL errors have a non-zero "library" code set in bits 24-32, and linux
// error codes should never go that high.
if (error.value() >= (1 << 24L)) {
evt.detail("WhichMeans", TLSPolicy::ErrorString(error));
}
if (peerAddr.isValid()) {
evt.detail("PeerAddr", peerAddr);
evt.detail("PeerAddress", peerAddr);
}
}
p.sendError(connection_failed());
} else
p.send(Void());
} catch (Error& e) {
p.sendError(e);
} catch (...) {
p.sendError(unknown_error());
}
}
};
class Connection final : public IConnection, ReferenceCounted<Connection> {
public:
void addref() override { ReferenceCounted<Connection>::addref(); }
void delref() override { ReferenceCounted<Connection>::delref(); }
void close() override { closeSocket(); }
explicit Connection(boost::asio::io_service& io_service)
: id(nondeterministicRandom()->randomUniqueID()), socket(io_service) {}
// This is not part of the IConnection interface, because it is wrapped by INetwork::connect()
ACTOR static Future<Reference<IConnection>> connect(boost::asio::io_service* ios, NetworkAddress addr) {
state Reference<Connection> self(new Connection(*ios));
self->peer_address = addr;
try {
auto to = tcpEndpoint(addr);
BindPromise p("N2_ConnectError", self->id);
Future<Void> onConnected = p.getFuture();
self->socket.async_connect(to, std::move(p));
wait(onConnected);
self->init();
return self;
} catch (Error&) {
// Either the connection failed, or was cancelled by the caller
self->closeSocket();
throw;
}
}
// This is not part of the IConnection interface, because it is wrapped by IListener::accept()
void accept(NetworkAddress peerAddr) {
this->peer_address = peerAddr;
init();
}
Future<Void> acceptHandshake() override { return Void(); }
Future<Void> connectHandshake() override { return Void(); }
// returns when write() can write at least one byte
Future<Void> onWritable() override {
++g_net2->countWriteProbes;
BindPromise p("N2_WriteProbeError", id);
auto f = p.getFuture();
socket.async_write_some(boost::asio::null_buffers(), std::move(p));
return f;
}
// returns when read() can read at least one byte
Future<Void> onReadable() override {
++g_net2->countReadProbes;
BindPromise p("N2_ReadProbeError", id);
auto f = p.getFuture();
socket.async_read_some(boost::asio::null_buffers(), std::move(p));
return f;
}
// Reads as many bytes as possible from the read buffer into [begin,end) and returns the number of bytes read (might
// be 0)
int read(uint8_t* begin, uint8_t* end) override {
boost::system::error_code err;
++g_net2->countReads;
size_t toRead = end - begin;
size_t size = socket.read_some(boost::asio::mutable_buffers_1(begin, toRead), err);
g_net2->bytesReceived += size;
//TraceEvent("ConnRead", this->id).detail("Bytes", size);
if (err) {
if (err == boost::asio::error::would_block) {
++g_net2->countWouldBlock;
return 0;
}
onReadError(err);
throw connection_failed();
}
ASSERT(size); // If the socket is closed, we expect an 'eof' error, not a zero return value
return size;
}
// Writes as many bytes as possible from the given SendBuffer chain into the write buffer and returns the number of
// bytes written (might be 0)
int write(SendBuffer const* data, int limit) override {
boost::system::error_code err;
++g_net2->countWrites;
size_t sent = socket.write_some(
boost::iterator_range<SendBufferIterator>(SendBufferIterator(data, limit), SendBufferIterator()), err);
if (err) {
// Since there was an error, sent's value can't be used to infer that the buffer has data and the limit is
// positive so check explicitly.
ASSERT(limit > 0);
bool notEmpty = false;
for (auto p = data; p; p = p->next)
if (p->bytes_written - p->bytes_sent > 0) {
notEmpty = true;
break;
}
ASSERT(notEmpty);
if (err == boost::asio::error::would_block) {
++g_net2->countWouldBlock;
return 0;
}
onWriteError(err);
throw connection_failed();
}
ASSERT(sent); // Make sure data was sent, and also this check will fail if the buffer chain was empty or the
// limit was not > 0.
return sent;
}
NetworkAddress getPeerAddress() const override { return peer_address; }
bool hasTrustedPeer() const override { return true; }
UID getDebugID() const override { return id; }
tcp::socket& getSocket() override { return socket; }
private:
UID id;
tcp::socket socket;
NetworkAddress peer_address;
void init() {
// Socket settings that have to be set after connect or accept succeeds
socket.non_blocking(true);
if (FLOW_KNOBS->FLOW_TCP_NODELAY & 1) {
socket.set_option(boost::asio::ip::tcp::no_delay(true));
}
if (FLOW_KNOBS->FLOW_TCP_QUICKACK & 1) {
#ifdef __linux__
socket.set_option(boost::asio::detail::socket_option::boolean<IPPROTO_TCP, TCP_QUICKACK>(true));
#else
TraceEvent(SevWarn, "N2_InitWarn").detail("Message", "TCP_QUICKACK not supported");
#endif
}
platform::setCloseOnExec(socket.native_handle());
}
void closeSocket() {
boost::system::error_code error;
socket.close(error);
if (error)
TraceEvent(SevWarn, "N2_CloseError", id)
.suppressFor(1.0)
.detail("PeerAddr", peer_address)
.detail("PeerAddress", peer_address)
.detail("ErrorCode", error.value())
.detail("Message", error.message());
}
void onReadError(const boost::system::error_code& error) {
TraceEvent(SevWarn, "N2_ReadError", id)
.suppressFor(1.0)
.detail("PeerAddr", peer_address)
.detail("PeerAddress", peer_address)
.detail("ErrorCode", error.value())
.detail("Message", error.message());
closeSocket();
}
void onWriteError(const boost::system::error_code& error) {
TraceEvent(SevWarn, "N2_WriteError", id)
.suppressFor(1.0)
.detail("PeerAddr", peer_address)
.detail("PeerAddress", peer_address)
.detail("ErrorCode", error.value())
.detail("Message", error.message());
closeSocket();
}
};
class ReadPromise {
Promise<int> p;
const char* errContext;
UID errID;
std::shared_ptr<udp::endpoint> endpoint = nullptr;
public:
ReadPromise(const char* errContext, UID errID) : errContext(errContext), errID(errID) {}
ReadPromise(ReadPromise const& other) = default;
ReadPromise(ReadPromise&& other) : p(std::move(other.p)), errContext(other.errContext), errID(other.errID) {}
std::shared_ptr<udp::endpoint>& getEndpoint() { return endpoint; }
Future<int> getFuture() { return p.getFuture(); }
void operator()(const boost::system::error_code& error, size_t bytesWritten) {
try {
if (error) {
TraceEvent evt(SevWarn, errContext, errID);
evt.suppressFor(1.0).detail("ErrorCode", error.value()).detail("Message", error.message());
p.sendError(connection_failed());
} else {
p.send(int(bytesWritten));
}
} catch (Error& e) {
p.sendError(e);
} catch (...) {
p.sendError(unknown_error());
}
}
};
class UDPSocket : public IUDPSocket, ReferenceCounted<UDPSocket> {
UID id;
Optional<NetworkAddress> toAddress;
udp::socket socket;
bool isPublic = false;
public:
ACTOR static Future<Reference<IUDPSocket>> connect(boost::asio::io_service* io_service,
Optional<NetworkAddress> toAddress,
bool isV6) {
state Reference<UDPSocket> self(new UDPSocket(*io_service, toAddress, isV6));
ASSERT(!toAddress.present() || toAddress.get().ip.isV6() == isV6);
if (!toAddress.present()) {
return self;
}
try {
if (toAddress.present()) {
auto to = udpEndpoint(toAddress.get());
BindPromise p("N2_UDPConnectError", self->id);
Future<Void> onConnected = p.getFuture();
self->socket.async_connect(to, std::move(p));
wait(onConnected);
}
self->init();
return self;
} catch (...) {
self->closeSocket();
throw;
}
}
void close() override { closeSocket(); }
Future<int> receive(uint8_t* begin, uint8_t* end) override {
++g_net2->countUDPReads;
ReadPromise p("N2_UDPReadError", id);
auto res = p.getFuture();
socket.async_receive(boost::asio::mutable_buffer(begin, end - begin), std::move(p));
return fmap(
[](int bytes) {
g_net2->udpBytesReceived += bytes;
return bytes;
},
res);
}
Future<int> receiveFrom(uint8_t* begin, uint8_t* end, NetworkAddress* sender) override {
++g_net2->countUDPReads;
ReadPromise p("N2_UDPReadFromError", id);
p.getEndpoint() = std::make_shared<udp::endpoint>();
auto endpoint = p.getEndpoint().get();
auto res = p.getFuture();
socket.async_receive_from(boost::asio::mutable_buffer(begin, end - begin), *endpoint, std::move(p));
return fmap(
[endpoint, sender](int bytes) {
if (sender) {
sender->port = endpoint->port();
sender->ip = toIPAddress(endpoint->address());
}
g_net2->udpBytesReceived += bytes;
return bytes;
},
res);
}
Future<int> send(uint8_t const* begin, uint8_t const* end) override {
++g_net2->countUDPWrites;
ReadPromise p("N2_UDPWriteError", id);
auto res = p.getFuture();
socket.async_send(boost::asio::const_buffer(begin, end - begin), std::move(p));
return res;
}
Future<int> sendTo(uint8_t const* begin, uint8_t const* end, NetworkAddress const& peer) override {
++g_net2->countUDPWrites;
ReadPromise p("N2_UDPWriteError", id);
auto res = p.getFuture();
udp::endpoint toEndpoint = udpEndpoint(peer);
socket.async_send_to(boost::asio::const_buffer(begin, end - begin), toEndpoint, std::move(p));
return res;
}
void bind(NetworkAddress const& addr) override {
boost::system::error_code ec;
socket.bind(udpEndpoint(addr), ec);
if (ec) {
Error x;
if (ec.value() == EADDRINUSE)
x = address_in_use();
else if (ec.value() == EADDRNOTAVAIL)
x = invalid_local_address();
else
x = bind_failed();
TraceEvent(SevWarnAlways, "Net2UDPBindError").error(x);
throw x;
}
isPublic = true;
}
UID getDebugID() const override { return id; }
void addref() override { ReferenceCounted<UDPSocket>::addref(); }
void delref() override { ReferenceCounted<UDPSocket>::delref(); }
NetworkAddress localAddress() const override {
auto endpoint = socket.local_endpoint();
return NetworkAddress(toIPAddress(endpoint.address()), endpoint.port(), isPublic, false);
}
boost::asio::ip::udp::socket::native_handle_type native_handle() override { return socket.native_handle(); }
private:
UDPSocket(boost::asio::io_service& io_service, Optional<NetworkAddress> toAddress, bool isV6)
: id(nondeterministicRandom()->randomUniqueID()), socket(io_service, isV6 ? udp::v6() : udp::v4()) {}
void closeSocket() {
boost::system::error_code error;
socket.close(error);
if (error)
TraceEvent(SevWarn, "N2_CloseError", id)
.suppressFor(1.0)
.detail("ErrorCode", error.value())
.detail("Message", error.message());
}
void onReadError(const boost::system::error_code& error) {
TraceEvent(SevWarn, "N2_UDPReadError", id)
.suppressFor(1.0)
.detail("ErrorCode", error.value())
.detail("Message", error.message());
closeSocket();
}
void onWriteError(const boost::system::error_code& error) {
TraceEvent(SevWarn, "N2_UDPWriteError", id)
.suppressFor(1.0)
.detail("ErrorCode", error.value())
.detail("Message", error.message());
closeSocket();
}
void init() {
socket.non_blocking(true);
platform::setCloseOnExec(socket.native_handle());
}
};
class Listener final : public IListener, ReferenceCounted<Listener> {
boost::asio::io_context& io_service;
NetworkAddress listenAddress;
tcp::acceptor acceptor;
public:
Listener(boost::asio::io_context& io_service, NetworkAddress listenAddress)
: io_service(io_service), listenAddress(listenAddress), acceptor(io_service, tcpEndpoint(listenAddress)) {
// when port 0 is passed in, a random port will be opened
// set listenAddress as the address with the actual port opened instead of port 0
if (listenAddress.port == 0) {
this->listenAddress =
NetworkAddress::parse(acceptor.local_endpoint().address().to_string().append(":").append(
std::to_string(acceptor.local_endpoint().port())));
}
platform::setCloseOnExec(acceptor.native_handle());
}
void addref() override { ReferenceCounted<Listener>::addref(); }
void delref() override { ReferenceCounted<Listener>::delref(); }
// Returns one incoming connection when it is available
Future<Reference<IConnection>> accept() override { return doAccept(this); }
NetworkAddress getListenAddress() const override { return listenAddress; }
private:
ACTOR static Future<Reference<IConnection>> doAccept(Listener* self) {
state Reference<Connection> conn(new Connection(self->io_service));
state tcp::acceptor::endpoint_type peer_endpoint;
try {
BindPromise p("N2_AcceptError", UID());
auto f = p.getFuture();
self->acceptor.async_accept(conn->getSocket(), peer_endpoint, std::move(p));
wait(f);
auto peer_address = peer_endpoint.address().is_v6() ? IPAddress(peer_endpoint.address().to_v6().to_bytes())
: IPAddress(peer_endpoint.address().to_v4().to_ulong());
conn->accept(NetworkAddress(peer_address, peer_endpoint.port()));
return conn;
} catch (...) {
conn->close();
throw;
}
}
};
typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket&> ssl_socket;
struct SSLHandshakerThread final : IThreadPoolReceiver {
SSLHandshakerThread() {}
void init() override {}
struct Handshake final : TypedAction<SSLHandshakerThread, Handshake> {
Handshake(ssl_socket& socket, ssl_socket::handshake_type type) : socket(socket), type(type) {}
double getTimeEstimate() const override { return 0.001; }
std::string getPeerAddress() const {
std::ostringstream o;
boost::system::error_code ec;
auto addr = socket.lowest_layer().remote_endpoint(ec);
o << (!ec.failed() ? addr.address().to_string() : std::string_view("0.0.0.0"));
return std::move(o).str();
}
ThreadReturnPromise<Void> done;
ssl_socket& socket;
ssl_socket::handshake_type type;
boost::system::error_code err;
};
void action(Handshake& h) {
try {
h.socket.next_layer().non_blocking(false, h.err);
if (!h.err.failed()) {
h.socket.handshake(h.type, h.err);
}
if (!h.err.failed()) {
h.socket.next_layer().non_blocking(true, h.err);
}
if (h.err.failed()) {
TraceEvent(SevWarn,
h.type == ssl_socket::handshake_type::client ? "N2_ConnectHandshakeError"_audit
: "N2_AcceptHandshakeError"_audit)
.detail("PeerAddr", h.getPeerAddress())
.detail("PeerAddress", h.getPeerAddress())
.detail("ErrorCode", h.err.value())
.detail("ErrorMsg", h.err.message().c_str())
.detail("BackgroundThread", true);
h.done.sendError(connection_failed());
} else {
h.done.send(Void());
}
} catch (...) {
TraceEvent(SevWarn,
h.type == ssl_socket::handshake_type::client ? "N2_ConnectHandshakeUnknownError"_audit
: "N2_AcceptHandshakeUnknownError"_audit)
.detail("PeerAddr", h.getPeerAddress())
.detail("PeerAddress", h.getPeerAddress())
.detail("BackgroundThread", true);
h.done.sendError(connection_failed());
}
}
};
class SSLConnection final : public IConnection, ReferenceCounted<SSLConnection> {
public:
void addref() override { ReferenceCounted<SSLConnection>::addref(); }
void delref() override { ReferenceCounted<SSLConnection>::delref(); }
void close() override { closeSocket(); }
explicit SSLConnection(boost::asio::io_service& io_service,
Reference<ReferencedObject<boost::asio::ssl::context>> context)
: id(nondeterministicRandom()->randomUniqueID()), socket(io_service), ssl_sock(socket, context->mutate()),
sslContext(context), has_trusted_peer(false) {}
explicit SSLConnection(Reference<ReferencedObject<boost::asio::ssl::context>> context, tcp::socket* existingSocket)
: id(nondeterministicRandom()->randomUniqueID()), socket(std::move(*existingSocket)),
ssl_sock(socket, context->mutate()), sslContext(context) {}
// This is not part of the IConnection interface, because it is wrapped by INetwork::connect()
ACTOR static Future<Reference<IConnection>> connect(boost::asio::io_service* ios,
Reference<ReferencedObject<boost::asio::ssl::context>> context,
NetworkAddress addr,
tcp::socket* existingSocket = nullptr) {
std::pair<IPAddress, uint16_t> peerIP = std::make_pair(addr.ip, addr.port);
auto iter(g_network->networkInfo.serverTLSConnectionThrottler.find(peerIP));
if (iter != g_network->networkInfo.serverTLSConnectionThrottler.end()) {
if (now() < iter->second.second) {
if (iter->second.first >= FLOW_KNOBS->TLS_CLIENT_CONNECTION_THROTTLE_ATTEMPTS) {
TraceEvent("TLSOutgoingConnectionThrottlingWarning").suppressFor(1.0).detail("PeerIP", addr);
wait(delay(FLOW_KNOBS->CONNECTION_MONITOR_TIMEOUT));
throw connection_failed();
}
} else {
g_network->networkInfo.serverTLSConnectionThrottler.erase(peerIP);
}
}
if (existingSocket != nullptr) {
Reference<SSLConnection> self(new SSLConnection(context, existingSocket));
self->peer_address = addr;
self->init();
return self;
}
state Reference<SSLConnection> self(new SSLConnection(*ios, context));
self->peer_address = addr;
try {
auto to = tcpEndpoint(self->peer_address);
BindPromise p("N2_ConnectError", self->id);
Future<Void> onConnected = p.getFuture();
self->socket.async_connect(to, std::move(p));
wait(onConnected);
self->init();
return self;
} catch (Error&) {
// Either the connection failed, or was cancelled by the caller
self->closeSocket();
throw;
}
}
// This is not part of the IConnection interface, because it is wrapped by IListener::accept()
void accept(NetworkAddress peerAddr) {
this->peer_address = peerAddr;
init();
}
ACTOR static void doAcceptHandshake(Reference<SSLConnection> self, Promise<Void> connected) {
state Hold<int> holder;
try {
Future<Void> onHandshook;
ConfigureSSLStream(N2::g_net2->activeTlsPolicy,
self->ssl_sock,
self->peer_address,
[conn = self.getPtr()](bool verifyOk) { conn->has_trusted_peer = verifyOk; });
// If the background handshakers are not all busy, use one
if (N2::g_net2->sslPoolHandshakesInProgress < N2::g_net2->sslHandshakerThreadsStarted) {
holder = Hold(&N2::g_net2->sslPoolHandshakesInProgress);
auto handshake =
new SSLHandshakerThread::Handshake(self->ssl_sock, boost::asio::ssl::stream_base::server);
onHandshook = handshake->done.getFuture();
N2::g_net2->sslHandshakerPool->post(handshake);
} else {
// Otherwise use flow network thread
BindPromise p("N2_AcceptHandshakeError"_audit, self->id);
p.setPeerAddr(self->getPeerAddress());
onHandshook = p.getFuture();
self->ssl_sock.async_handshake(boost::asio::ssl::stream_base::server, std::move(p));
}
wait(onHandshook);
wait(delay(0, TaskPriority::Handshake));
connected.send(Void());
} catch (...) {
self->closeSocket();
connected.sendError(connection_failed());
}
}
ACTOR static Future<Void> acceptHandshakeWrapper(Reference<SSLConnection> self) {
state std::pair<IPAddress, uint16_t> peerIP;
peerIP = std::make_pair(self->getPeerAddress().ip, static_cast<uint16_t>(0));
auto iter(g_network->networkInfo.serverTLSConnectionThrottler.find(peerIP));
if (iter != g_network->networkInfo.serverTLSConnectionThrottler.end()) {
if (now() < iter->second.second) {
if (iter->second.first >= FLOW_KNOBS->TLS_SERVER_CONNECTION_THROTTLE_ATTEMPTS) {
TraceEvent("TLSIncomingConnectionThrottlingWarning")
.suppressFor(1.0)
.detail("PeerIP", peerIP.first.toString());
wait(delay(FLOW_KNOBS->CONNECTION_MONITOR_TIMEOUT));
self->closeSocket();
throw connection_failed();
}
} else {
g_network->networkInfo.serverTLSConnectionThrottler.erase(peerIP);
}
}
wait(g_network->networkInfo.handshakeLock->take());
state FlowLock::Releaser releaser(*g_network->networkInfo.handshakeLock);
Promise<Void> connected;
doAcceptHandshake(self, connected);
try {
choose {
when(wait(connected.getFuture())) {
return Void();
}
when(wait(delay(FLOW_KNOBS->CONNECTION_MONITOR_TIMEOUT))) {
throw connection_failed();
}
}
} catch (Error& e) {