-
Notifications
You must be signed in to change notification settings - Fork 937
Expand file tree
/
Copy pathTCPTransportInterface.cpp
More file actions
2209 lines (1956 loc) · 77.3 KB
/
Copy pathTCPTransportInterface.cpp
File metadata and controls
2209 lines (1956 loc) · 77.3 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
// Copyright 2018 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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 "TCPTransportInterface.h"
#include <algorithm>
#include <cassert>
#include <chrono>
#include <cstring>
#include <limits>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <thread>
#include <utility>
#include <vector>
#include <asio/executor_work_guard.hpp>
#include <asio/io_context.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/socket_base.hpp>
#include <asio/steady_timer.hpp>
#include <asio/system_error.hpp>
#if TLS_FOUND
#include <asio/ssl/verify_context.hpp>
#endif // if TLS_FOUND
#include <fastdds/dds/log/Log.hpp>
#include <fastdds/rtps/attributes/PropertyPolicy.h>
#include <fastdds/rtps/common/CDRMessage_t.h>
#include <fastdds/rtps/common/LocatorSelector.hpp>
#include <fastdds/rtps/common/LocatorSelectorEntry.hpp>
#include <fastdds/rtps/common/PortParameters.h>
#include <fastdds/rtps/common/Types.h>
#include <fastdds/rtps/transport/SenderResource.h>
#include <fastdds/rtps/transport/SocketTransportDescriptor.h>
#include <fastdds/rtps/transport/TCPTransportDescriptor.h>
#include <fastdds/rtps/transport/TransportReceiverInterface.h>
#include <fastrtps/config.h>
#include <fastrtps/utils/IPLocator.h>
#include <fastrtps/utils/System.h>
#include <rtps/transport/asio_helpers.hpp>
#include <statistics/rtps/messages/RTPSStatisticsMessages.hpp>
#include <utils/SystemInfo.hpp>
#include <utils/thread.hpp>
#include <utils/threading.hpp>
#include "tcp/RTCPHeader.h"
#include "tcp/RTCPMessageManager.h"
#include "TCPAcceptorBasic.h"
#include "TCPChannelResourceBasic.h"
#include "TCPSenderResource.hpp"
#if TLS_FOUND
#include "TCPAcceptorSecure.h"
#include "TCPChannelResourceSecure.h"
#endif // if TLS_FOUND
using namespace std;
using namespace asio;
namespace eprosima {
namespace fastdds {
namespace rtps {
using octet = fastrtps::rtps::octet;
using IPLocator = fastrtps::rtps::IPLocator;
using SenderResource = fastrtps::rtps::SenderResource;
using CDRMessage_t = fastrtps::rtps::CDRMessage_t;
using LocatorSelector = fastrtps::rtps::LocatorSelector;
using LocatorSelectorEntry = fastrtps::rtps::LocatorSelectorEntry;
using PortParameters = fastrtps::rtps::PortParameters;
using Log = fastdds::dds::Log;
static const int s_default_keep_alive_frequency = 5000; // 5 SECONDS
static const int s_default_keep_alive_timeout = 15000; // 15 SECONDS
//static const int s_clean_deleted_sockets_pool_timeout = 100; // 100 MILLISECONDS
TCPTransportDescriptor::TCPTransportDescriptor()
: SocketTransportDescriptor(s_maximumMessageSize, s_maximumInitialPeersRange)
, keep_alive_frequency_ms(s_default_keep_alive_frequency)
, keep_alive_timeout_ms(s_default_keep_alive_timeout)
, max_logical_port(100)
, logical_port_range(20)
, logical_port_increment(2)
, tcp_negotiation_timeout(0)
, enable_tcp_nodelay(false)
, wait_for_tcp_negotiation(false)
, calculate_crc(true)
, check_crc(true)
, apply_security(false)
, non_blocking_send(false)
{
}
TCPTransportDescriptor::TCPTransportDescriptor(
const TCPTransportDescriptor& t)
: SocketTransportDescriptor(t)
, listening_ports(t.listening_ports)
, keep_alive_frequency_ms(t.keep_alive_frequency_ms)
, keep_alive_timeout_ms(t.keep_alive_timeout_ms)
, max_logical_port(t.max_logical_port)
, logical_port_range(t.logical_port_range)
, logical_port_increment(t.logical_port_increment)
, tcp_negotiation_timeout(t.tcp_negotiation_timeout)
, enable_tcp_nodelay(t.enable_tcp_nodelay)
, wait_for_tcp_negotiation(t.wait_for_tcp_negotiation)
, calculate_crc(t.calculate_crc)
, check_crc(t.check_crc)
, apply_security(t.apply_security)
, tls_config(t.tls_config)
, keep_alive_thread(t.keep_alive_thread)
, accept_thread(t.accept_thread)
, non_blocking_send(t.non_blocking_send)
{
}
TCPTransportDescriptor& TCPTransportDescriptor::operator =(
const TCPTransportDescriptor& t)
{
SocketTransportDescriptor::operator =(t);
listening_ports = t.listening_ports;
keep_alive_frequency_ms = t.keep_alive_frequency_ms;
keep_alive_timeout_ms = t.keep_alive_timeout_ms;
max_logical_port = t.max_logical_port;
logical_port_range = t.logical_port_range;
logical_port_increment = t.logical_port_increment;
tcp_negotiation_timeout = t.tcp_negotiation_timeout;
enable_tcp_nodelay = t.enable_tcp_nodelay;
wait_for_tcp_negotiation = t.wait_for_tcp_negotiation;
calculate_crc = t.calculate_crc;
check_crc = t.check_crc;
apply_security = t.apply_security;
tls_config = t.tls_config;
keep_alive_thread = t.keep_alive_thread;
accept_thread = t.accept_thread;
non_blocking_send = t.non_blocking_send;
return *this;
}
bool TCPTransportDescriptor::operator ==(
const TCPTransportDescriptor& t) const
{
return (this->listening_ports == t.listening_ports &&
this->keep_alive_frequency_ms == t.keep_alive_frequency_ms &&
this->keep_alive_timeout_ms == t.keep_alive_timeout_ms &&
this->max_logical_port == t.max_logical_port &&
this->logical_port_range == t.logical_port_range &&
this->logical_port_increment == t.logical_port_increment &&
this->tcp_negotiation_timeout == t.tcp_negotiation_timeout &&
this->enable_tcp_nodelay == t.enable_tcp_nodelay &&
this->wait_for_tcp_negotiation == t.wait_for_tcp_negotiation &&
this->calculate_crc == t.calculate_crc &&
this->check_crc == t.check_crc &&
this->apply_security == t.apply_security &&
this->tls_config == t.tls_config &&
this->keep_alive_thread == t.keep_alive_thread &&
this->accept_thread == t.accept_thread &&
this->non_blocking_send == t.non_blocking_send &&
SocketTransportDescriptor::operator ==(t));
}
TCPTransportInterface::TCPTransportInterface(
int32_t transport_kind)
: TransportInterface(transport_kind)
, alive_(true)
#if TLS_FOUND
, ssl_context_(asio::ssl::context::sslv23)
#endif // if TLS_FOUND
, keep_alive_event_(io_context_timers_)
{
}
TCPTransportInterface::~TCPTransportInterface()
{
}
void TCPTransportInterface::clean()
{
assert(receiver_resources_.size() == 0);
alive_.store(false);
keep_alive_event_.cancel();
if (io_context_timers_thread_.joinable())
{
io_context_timers_.stop();
io_context_timers_thread_.join();
}
{
std::vector<std::shared_ptr<TCPChannelResource>> channels;
std::vector<eprosima::fastdds::rtps::Locator> delete_channels;
{
std::unique_lock<std::mutex> scopedLock(sockets_map_mutex_);
std::unique_lock<std::mutex> unbound_lock(unbound_map_mutex_);
channels = unbound_channel_resources_;
for (auto& channel : channel_resources_)
{
if (std::find(channels.begin(), channels.end(), channel.second) == channels.end())
{
channels.push_back(channel.second);
}
else
{
delete_channels.push_back(channel.first);
}
}
}
for (auto& delete_channel : delete_channels)
{
channel_resources_.erase(delete_channel);
}
for (auto& channel : channels)
{
if (channel->connection_established())
{
rtcp_message_manager_->sendUnbindConnectionRequest(channel);
}
channel->disconnect();
channel->clear();
}
std::unique_lock<std::mutex> lock(rtcp_message_manager_mutex_);
rtcp_message_manager_cv_.wait(lock, [&]()
{
return 1 >= rtcp_message_manager_.use_count();
});
if (rtcp_message_manager_)
{
rtcp_message_manager_->dispose();
rtcp_message_manager_.reset();
}
}
if (initial_peer_local_locator_socket_)
{
if (initial_peer_local_locator_socket_->is_open())
{
initial_peer_local_locator_socket_->close();
}
initial_peer_local_locator_socket_.reset();
}
if (io_context_thread_.joinable())
{
io_context_.stop();
io_context_thread_.join();
}
}
Locator TCPTransportInterface::remote_endpoint_to_locator(
const std::shared_ptr<TCPChannelResource>& channel) const
{
Locator locator;
asio::error_code ec;
auto endpoint = channel->remote_endpoint(ec);
if (ec)
{
LOCATOR_INVALID(locator);
}
else
{
endpoint_to_locator(endpoint, locator);
}
return locator;
}
Locator TCPTransportInterface::local_endpoint_to_locator(
const std::shared_ptr<TCPChannelResource>& channel) const
{
Locator locator;
asio::error_code ec;
auto endpoint = channel->local_endpoint(ec);
if (ec)
{
LOCATOR_INVALID(locator);
}
else
{
endpoint_to_locator(endpoint, locator);
}
return locator;
}
ResponseCode TCPTransportInterface::bind_socket(
std::shared_ptr<TCPChannelResource>& channel)
{
std::unique_lock<std::mutex> scopedLock(sockets_map_mutex_);
std::unique_lock<std::mutex> unbound_lock(unbound_map_mutex_);
auto it_remove = std::find(unbound_channel_resources_.begin(), unbound_channel_resources_.end(), channel);
assert(it_remove != unbound_channel_resources_.end());
unbound_channel_resources_.erase(it_remove);
ResponseCode ret = RETCODE_OK;
const auto insert_ret = channel_resources_.insert(
decltype(channel_resources_)::value_type{channel->locator(), channel});
if (false == insert_ret.second)
{
// There is an existing channel that can be used. Force the Client to close unnecessary socket
ret = RETCODE_SERVER_ERROR;
}
std::vector<fastrtps::rtps::IPFinder::info_IP> local_interfaces;
// Check if the locator is from an owned interface to link all local interfaces to the channel
// Note: Only applicable for TCPv4 until TCPv6 scope selection is implemented
if (channel->locator().kind != LOCATOR_KIND_TCPv6)
{
is_own_interface(channel->locator(), local_interfaces);
if (!local_interfaces.empty())
{
Locator local_locator(channel->locator());
for (auto& interface_it : local_interfaces)
{
IPLocator::copy_address(interface_it.locator, local_locator);
channel_resources_.insert(decltype(channel_resources_)::value_type{local_locator, channel});
}
}
}
return ret;
}
bool TCPTransportInterface::check_crc(
const TCPHeader& header,
const octet* data,
uint32_t size) const
{
uint32_t crc(0);
for (uint32_t i = 0; i < size; ++i)
{
crc = RTCPMessageManager::addToCRC(crc, data[i]);
}
return crc == header.crc;
}
void TCPTransportInterface::calculate_crc(
TCPHeader& header,
const octet* data,
uint32_t size) const
{
uint32_t crc(0);
for (uint32_t i = 0; i < size; ++i)
{
crc = RTCPMessageManager::addToCRC(crc, data[i]);
}
header.crc = crc;
}
uint16_t TCPTransportInterface::create_acceptor_socket(
const Locator& locator)
{
uint16_t final_port = 0;
try
{
if (is_interface_whitelist_empty())
{
#if TLS_FOUND
if (configuration()->apply_security)
{
std::shared_ptr<TCPAcceptorSecure> acceptor =
std::make_shared<TCPAcceptorSecure>(io_context_, this, locator);
acceptors_[acceptor->locator()] = acceptor;
acceptor->accept(this, ssl_context_);
final_port = static_cast<uint16_t>(acceptor->locator().port);
}
else
#endif // if TLS_FOUND
{
std::shared_ptr<TCPAcceptorBasic> acceptor =
std::make_shared<TCPAcceptorBasic>(io_context_, this, locator);
acceptors_[acceptor->locator()] = acceptor;
acceptor->accept(this);
final_port = static_cast<uint16_t>(acceptor->locator().port);
}
EPROSIMA_LOG_INFO(RTCP, " OpenAndBindInput (physical: " << IPLocator::getPhysicalPort(
locator) << "; logical: "
<< IPLocator::getLogicalPort(locator) << ")");
}
else
{
std::vector<std::string> vInterfaces = get_binding_interfaces_list();
for (std::string& sInterface : vInterfaces)
{
Locator loc = locator;
if (loc.kind == LOCATOR_KIND_TCPv4)
{
IPLocator::setIPv4(loc, sInterface);
}
else if (loc.kind == LOCATOR_KIND_TCPv6)
{
IPLocator::setIPv6(loc, sInterface);
}
#if TLS_FOUND
if (configuration()->apply_security)
{
std::shared_ptr<TCPAcceptorSecure> acceptor =
std::make_shared<TCPAcceptorSecure>(io_context_, sInterface, loc);
acceptors_[acceptor->locator()] = acceptor;
acceptor->accept(this, ssl_context_);
final_port = static_cast<uint16_t>(acceptor->locator().port);
}
else
#endif // if TLS_FOUND
{
std::shared_ptr<TCPAcceptorBasic> acceptor =
std::make_shared<TCPAcceptorBasic>(io_context_, sInterface, loc);
acceptors_[acceptor->locator()] = acceptor;
acceptor->accept(this);
final_port = static_cast<uint16_t>(acceptor->locator().port);
}
EPROSIMA_LOG_INFO(RTCP, " OpenAndBindInput (physical: " << IPLocator::getPhysicalPort(
locator) << "; logical: "
<< IPLocator::getLogicalPort(locator) << ")");
}
}
}
catch (asio::system_error const& e)
{
(void)e;
EPROSIMA_LOG_ERROR(RTCP_MSG_OUT, "TCPTransport Error binding at port: (" << IPLocator::getPhysicalPort(
locator) << ")" << " with msg: " << e.what());
return false;
}
catch (const asio::error_code& code)
{
(void)code;
EPROSIMA_LOG_ERROR(RTCP, "TCPTransport Error binding at port: (" << IPLocator::getPhysicalPort(
locator) << ")" << " with code: " << code);
return false;
}
return final_port;
}
void TCPTransportInterface::fill_rtcp_header(
TCPHeader& header,
const octet* send_buffer,
uint32_t send_buffer_size,
uint16_t logical_port) const
{
header.length = send_buffer_size + static_cast<uint32_t>(TCPHeader::size());
header.logical_port = logical_port;
if (configuration()->calculate_crc)
{
calculate_crc(header, send_buffer, send_buffer_size);
}
}
bool TCPTransportInterface::DoInputLocatorsMatch(
const Locator& left,
const Locator& right) const
{
return IPLocator::getPhysicalPort(left) == IPLocator::getPhysicalPort(right);
}
bool TCPTransportInterface::init(
const fastrtps::rtps::PropertyPolicy*,
const uint32_t& max_msg_size_no_frag)
{
uint32_t maximumMessageSize = max_msg_size_no_frag == 0 ? s_maximumMessageSize : max_msg_size_no_frag;
uint32_t cfg_max_msg_size = configuration()->maxMessageSize;
uint32_t cfg_send_size = configuration()->sendBufferSize;
uint32_t cfg_recv_size = configuration()->receiveBufferSize;
uint32_t max_int_value = static_cast<uint32_t>(std::numeric_limits<int32_t>::max());
if (cfg_max_msg_size > maximumMessageSize)
{
EPROSIMA_LOG_ERROR(TRANSPORT_TCP, "maxMessageSize cannot be greater than " << maximumMessageSize);
return false;
}
if (cfg_send_size > max_int_value)
{
EPROSIMA_LOG_ERROR(TRANSPORT_TCP, "sendBufferSize cannot be greater than " << max_int_value);
return false;
}
if (cfg_recv_size > max_int_value)
{
EPROSIMA_LOG_ERROR(TRANSPORT_TCP, "receiveBufferSize cannot be greater than " << max_int_value);
return false;
}
if ((cfg_send_size > 0) && (cfg_max_msg_size > cfg_send_size))
{
EPROSIMA_LOG_ERROR(TRANSPORT_TCP, "maxMessageSize cannot be greater than sendBufferSize");
return false;
}
if ((cfg_recv_size > 0) && (cfg_max_msg_size > cfg_recv_size))
{
EPROSIMA_LOG_ERROR(TRANSPORT_TCP, "maxMessageSize cannot be greater than receiveBufferSize");
return false;
}
if (!apply_tls_config())
{
// TODO decide wether the Transport initialization should keep working after this error
EPROSIMA_LOG_WARNING(TLS, "Error configuring TLS, using TCP transport without security");
}
/*
Open and bind a socket to obtain a unique port. This port is assigned to PDP passed locators.
Although real client socket local port will differ, this ensures uniqueness for server's channel
resources mapping (uses client locators as keys).
Open and bind a socket to obtain a unique port. This unique port is assigned to to PDP passed locators.
This process ensures uniqueness in the server's channel resources mapping, which uses client locators as keys.
Although differing from the real client socket local port, provides a reliable mapping mechanism.
*/
initial_peer_local_locator_socket_ = std::unique_ptr<asio::ip::tcp::socket>(new asio::ip::tcp::socket(io_context_));
initial_peer_local_locator_socket_->open(generate_protocol());
// Binding to port 0 delegates the port selection to the system.
initial_peer_local_locator_socket_->bind(asio::ip::tcp::endpoint(generate_protocol(), 0));
ip::tcp::endpoint local_endpoint = initial_peer_local_locator_socket_->local_endpoint();
initial_peer_local_locator_port_ = local_endpoint.port();
// Check system buffer sizes.
uint32_t send_size = 0;
uint32_t recv_size = 0;
if (!asio_helpers::configure_buffer_sizes(
*initial_peer_local_locator_socket_, *configuration(), send_size, recv_size))
{
EPROSIMA_LOG_ERROR(TRANSPORT_TCP, "Couldn't set buffer sizes to minimum value: " << cfg_max_msg_size);
return false;
}
if (cfg_send_size > 0 && send_size != cfg_send_size)
{
EPROSIMA_LOG_WARNING(TRANSPORT_TCP, "TCPTransport sendBufferSize could not be set to the desired value. "
<< "Using " << send_size << " instead of " << cfg_send_size);
}
if (cfg_recv_size > 0 && recv_size != cfg_recv_size)
{
EPROSIMA_LOG_WARNING(TRANSPORT_TCP, "TCPTransport receiveBufferSize could not be set to the desired value. "
<< "Using " << recv_size << " instead of " << cfg_recv_size);
}
set_send_buffer_size(send_size);
set_receive_buffer_size(recv_size);
if (!rtcp_message_manager_)
{
rtcp_message_manager_ = std::make_shared<RTCPMessageManager>(this);
}
auto ioContextFunction = [&]()
{
asio::executor_work_guard<asio::io_context::executor_type> work = make_work_guard(io_context_);
io_context_.run();
};
io_context_thread_ = create_thread(ioContextFunction, configuration()->accept_thread, "dds.tcp_accept");
if (0 < configuration()->keep_alive_frequency_ms)
{
auto ioContextTimersFunction = [&]()
{
asio::executor_work_guard<asio::io_context::executor_type> work = make_work_guard(io_context_timers_.
get_executor());
io_context_timers_.run();
};
io_context_timers_thread_ = create_thread(ioContextTimersFunction,
configuration()->keep_alive_thread, "dds.tcp_keep");
}
return true;
}
bool TCPTransportInterface::is_input_port_open(
uint16_t port) const
{
std::unique_lock<std::mutex> scopedLock(sockets_map_mutex_);
return receiver_resources_.find(port) != receiver_resources_.end();
}
bool TCPTransportInterface::IsInputChannelOpen(
const Locator& locator) const
{
return IsLocatorSupported(locator) && is_input_port_open(IPLocator::getLogicalPort(locator));
}
bool TCPTransportInterface::IsLocatorSupported(
const Locator& locator) const
{
return locator.kind == transport_kind_;
}
bool TCPTransportInterface::is_output_channel_open_for(
const Locator& locator) const
{
if (!IsLocatorSupported(locator))
{
return false;
}
std::unique_lock<std::mutex> scopedLock(sockets_map_mutex_);
// Check if there is any socket opened with the given locator.
auto channel_resource = channel_resources_.find(IPLocator::toPhysicalLocator(locator));
if (channel_resource != channel_resources_.end())
{
// And it is registered as output logical port
return channel_resource->second->is_logical_port_added(IPLocator::getLogicalPort(locator));
}
return false;
}
Locator TCPTransportInterface::RemoteToMainLocal(
const Locator& remote) const
{
if (!IsLocatorSupported(remote))
{
return false;
}
Locator mainLocal(remote);
mainLocal.set_Invalid_Address();
return mainLocal;
}
bool TCPTransportInterface::transform_remote_locator(
const Locator& remote_locator,
Locator& result_locator,
bool allowed_remote_localhost,
bool allowed_local_localhost) const
{
if (IsLocatorSupported(remote_locator))
{
result_locator = remote_locator;
if (!is_local_locator(result_locator))
{
// is_local_locator will return false for multicast addresses as well as remote unicast ones.
return true;
}
// If we get here, the locator is a local unicast address
// Attempt conversion to localhost if remote transport listening on it allows it
if (allowed_remote_localhost)
{
Locator loopbackLocator;
fill_local_ip(loopbackLocator);
if (is_locator_allowed(loopbackLocator))
{
// Locator localhost is in the whitelist, so use localhost instead of remote_locator
fill_local_ip(result_locator);
IPLocator::setPhysicalPort(result_locator, IPLocator::getPhysicalPort(remote_locator));
IPLocator::setLogicalPort(result_locator, IPLocator::getLogicalPort(remote_locator));
return true;
}
else if (allowed_local_localhost)
{
// Abort transformation if localhost not allowed by this transport, but it is by other local transport
// and the remote one.
return false;
}
}
if (!is_locator_allowed(result_locator))
{
// Neither original remote locator nor localhost allowed: abort.
return false;
}
return true;
}
return false;
}
void TCPTransportInterface::SenderResourceHasBeenClosed(
fastrtps::rtps::Locator_t& locator)
{
// The TCPSendResource associated channel cannot be removed from the channel_resources_ map. On transport's destruction
// this map is consulted to send the unbind requests. If not sending it, the other participant wouldn't disconnect the
// socket and keep a connection status of eEstablished. This would prevent new connect calls since it thinks it's already
// connected.
// If moving this unbind send with the respective channel disconnection to this point, the following problem arises:
// If receiving a SenderResourceHasBeenClosed call after receiving an unbinding message from a remote participant (our participant
// isn't disconnecting but we want to erase this send resource), the channel cannot be disconnected here since the listening thread has
// taken the read mutex (permanently waiting at read asio layer). This mutex is also needed to disconnect the socket (deadlock).
// Socket disconnection should always be done in the listening thread (or in the transport cleanup, when receiver resources have
// already been destroyed and the listening thread had consequently finished).
// An assert() clause finding the respective channel resource cannot be made since in LARGE DATA scenario, where the PDP discovery is done
// via UDP, a server's send resource can be created without any associated channel resource until receiving a connection request from
// the client.
// The send resource locator is invalidated to prevent further use of associated channel.
LOCATOR_INVALID(locator);
}
bool TCPTransportInterface::CloseInputChannel(
const Locator& locator)
{
bool bClosed = false;
{
std::unique_lock<std::mutex> scopedLock(sockets_map_mutex_);
uint16_t logicalPort = IPLocator::getLogicalPort(locator);
auto receiverIt = receiver_resources_.find(logicalPort);
if (receiverIt != receiver_resources_.end())
{
bClosed = true;
ReceiverInUseCV* receiver_in_use = receiverIt->second.second;
receiver_resources_.erase(receiverIt);
// Inform all channel resources that logical port has been closed
for (auto channelIt : channel_resources_)
{
if (channelIt.second->connection_established())
{
rtcp_message_manager_->sendLogicalPortIsClosedRequest(channelIt.second, logicalPort);
}
}
receiver_in_use->cv.wait(scopedLock, [&]()
{
return receiver_in_use->in_use == 0;
});
delete receiver_in_use;
}
}
return bClosed;
}
void TCPTransportInterface::close_tcp_socket(
std::shared_ptr<TCPChannelResource>& channel)
{
channel->disconnect();
// channel.reset(); lead to race conditions because TransportInterface functions used in the callbacks doesn't check validity.
}
bool TCPTransportInterface::OpenOutputChannel(
SendResourceList& send_resource_list,
const Locator& locator)
{
if (!IsLocatorSupported(locator))
{
return false;
}
uint16_t logical_port = IPLocator::getLogicalPort(locator);
if (0 == logical_port)
{
return false;
}
Locator physical_locator = IPLocator::toPhysicalLocator(locator);
std::lock_guard<std::mutex> socketsLock(sockets_map_mutex_);
// We try to find a SenderResource that has this locator.
// Note: This is done in this level because if we do in NetworkFactory level, we have to mantain what transport
// already reuses a SenderResource.
for (auto& sender_resource : send_resource_list)
{
TCPSenderResource* tcp_sender_resource = TCPSenderResource::cast(*this, sender_resource.get());
if (tcp_sender_resource && (physical_locator == tcp_sender_resource->locator() ||
(IPLocator::hasWan(locator) &&
IPLocator::WanToLanLocator(physical_locator) ==
tcp_sender_resource->locator())))
{
// Add logical port to channel if it's not there yet
auto channel_resource = channel_resources_.find(physical_locator);
// Maybe as WAN?
if (channel_resource == channel_resources_.end() && IPLocator::hasWan(locator))
{
Locator wan_locator = IPLocator::WanToLanLocator(locator);
channel_resource = channel_resources_.find(IPLocator::toPhysicalLocator(wan_locator));
}
if (channel_resource != channel_resources_.end())
{
channel_resource->second->add_logical_port(logical_port, rtcp_message_manager_.get());
}
else
{
std::lock_guard<std::mutex> channelPendingLock(channel_pending_logical_ports_mutex_);
channel_pending_logical_ports_[physical_locator].insert(logical_port);
}
statistics_info_.add_entry(locator);
return true;
}
}
// At this point, if there is no SenderResource to reuse, this is the first call to OpenOutputChannel for this locator.
// Need to check if a channel already exists for this locator.
EPROSIMA_LOG_INFO(RTCP, "Called to OpenOutputChannel @ " << IPLocator::to_string(locator));
auto channel_resource = channel_resources_.find(physical_locator);
// Maybe as WAN?
if (channel_resource == channel_resources_.end() && IPLocator::hasWan(locator))
{
Locator wan_locator = IPLocator::WanToLanLocator(locator);
channel_resource = channel_resources_.find(IPLocator::toPhysicalLocator(wan_locator));
if (channel_resource != channel_resources_.end())
{
channel_resources_[physical_locator] = channel_resource->second; // Add alias!
}
}
// (Server-Client Topology OR LARGE DATA with PDP discovery after TCP connection) - Server side
if (channel_resource != channel_resources_.end())
{
std::shared_ptr<TCPChannelResource> channel;
// There is an existing channel in channel_resources_ created for reception with the remote locator as key. Use it.
channel = channel_resource->second;
// Add logical port to channel if it's not there yet
channel->add_logical_port(logical_port, rtcp_message_manager_.get());
}
// (Server-Client Topology - Client Side) OR LARGE DATA Topology with PDP discovery before TCP connection
else
{
// Get listening port (0 if client)
uint16_t listening_port = 0;
const TCPTransportDescriptor* config = configuration();
assert (config != nullptr);
if (!config->listening_ports.empty())
{
listening_port = config->listening_ports.front();
}
bool local_lower_interface = false;
if (IPLocator::getPhysicalPort(physical_locator) == listening_port)
{
std::vector<Locator> list;
std::vector<fastrtps::rtps::IPFinder::info_IP> local_interfaces;
get_ips(local_interfaces, false, false);
for (const auto& interface_it : local_interfaces)
{
Locator interface_loc(interface_it.locator);
interface_loc.port = physical_locator.port;
if (is_interface_allowed(interface_loc))
{
list.push_back(interface_loc);
}
}
if (!list.empty() && (list.front() < physical_locator))
{
local_lower_interface = true;
}
}
// If the remote physical port is higher than our listening port, a new CONNECT channel needs to be created and connected
// and the locator added to the send_resource_list.
// If the remote physical port is lower than our listening port, only the locator needs to be added to the send_resource_list.
if (IPLocator::getPhysicalPort(physical_locator) > listening_port || local_lower_interface)
{
// Client side (either Server-Client or LARGE_DATA)
EPROSIMA_LOG_INFO(RTCP, "OpenOutputChannel: [CONNECT] @ " << IPLocator::to_string(locator));
// Create a TCP_CONNECT_TYPE channel
std::shared_ptr<TCPChannelResource> channel(
#if TLS_FOUND
(configuration()->apply_security) ?
static_cast<TCPChannelResource*>(
new TCPChannelResourceSecure(this, io_context_, ssl_context_,
physical_locator, configuration()->maxMessageSize)) :
#endif // if TLS_FOUND
static_cast<TCPChannelResource*>(
new TCPChannelResourceBasic(this, io_context_, physical_locator,
configuration()->maxMessageSize))
);
channel_resources_[physical_locator] = channel;
channel->connect(channel_resources_[physical_locator]);
channel->add_logical_port(logical_port, rtcp_message_manager_.get());
}
else
{
// Server side LARGE_DATA
// Act as server and wait to the other endpoint to connect. Add locator to sender_resource_list
EPROSIMA_LOG_INFO(RTCP,
"OpenOutputChannel: [WAIT_CONNECTION] @ " << IPLocator::to_string(locator));
std::lock_guard<std::mutex> channelPendingLock(channel_pending_logical_ports_mutex_);
channel_pending_logical_ports_[physical_locator].insert(logical_port);
}
}
statistics_info_.add_entry(locator);
send_resource_list.emplace_back(
static_cast<SenderResource*>(new TCPSenderResource(*this, physical_locator)));
return true;
}
bool TCPTransportInterface::OpenOutputChannels(
SendResourceList& send_resource_list,
const LocatorSelectorEntry& locator_selector_entry)
{
bool success = false;
if (locator_selector_entry.remote_guid == fastrtps::rtps::c_Guid_Unknown)
{
// Only unicast is used in TCP
for (size_t i = 0; i < locator_selector_entry.state.unicast.size(); ++i)
{
size_t index = locator_selector_entry.state.unicast[i];
success |= CreateInitialConnect(send_resource_list, locator_selector_entry.unicast[index]);
}
}
else
{
for (size_t i = 0; i < locator_selector_entry.state.unicast.size(); ++i)
{
size_t index = locator_selector_entry.state.unicast[i];
success |= OpenOutputChannel(send_resource_list, locator_selector_entry.unicast[index]);
}
}
return success;
}
bool TCPTransportInterface::CreateInitialConnect(
SendResourceList& send_resource_list,
const Locator& locator)
{
if (!IsLocatorSupported(locator))
{
return false;
}
uint16_t logical_port = IPLocator::getLogicalPort(locator);
if (0 == logical_port)
{
return false;
}
Locator physical_locator = IPLocator::toPhysicalLocator(locator);
std::lock_guard<std::mutex> socketsLock(sockets_map_mutex_);
// We try to find a SenderResource that has this locator.
// Note: This is done in this level because if we do it at NetworkFactory level, we have to mantain what transport
// already reuses a SenderResource.
for (auto& sender_resource : send_resource_list)
{
TCPSenderResource* tcp_sender_resource = TCPSenderResource::cast(*this, sender_resource.get());
if (tcp_sender_resource && (physical_locator == tcp_sender_resource->locator() ||
(IPLocator::hasWan(locator) &&
IPLocator::WanToLanLocator(physical_locator) ==
tcp_sender_resource->locator())))
{
// Add logical port to channel if it's not there yet
auto channel_resource = channel_resources_.find(physical_locator);
// Maybe as WAN?
if (channel_resource == channel_resources_.end() && IPLocator::hasWan(locator))
{
Locator wan_locator = IPLocator::WanToLanLocator(locator);
channel_resource = channel_resources_.find(IPLocator::toPhysicalLocator(wan_locator));
}
if (channel_resource != channel_resources_.end())
{
channel_resource->second->add_logical_port(logical_port, rtcp_message_manager_.get());
}
else
{
std::lock_guard<std::mutex> channelPendingLock(channel_pending_logical_ports_mutex_);
channel_pending_logical_ports_[physical_locator].insert(logical_port);
}
statistics_info_.add_entry(locator);
return true;
}
}
// At this point, if there is no SenderResource to reuse, this is the first try to open a channel for this locator.