1 /*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11 /*
12 * This is a diagram of how TCP reconnect works for the active side. The
13 * passive side just waits for an incoming connection.
14 *
15 * - Connected: Indicate whether the TCP socket is connected.
16 *
17 * - Writable: Whether the stun binding is completed. Sending a data packet
18 * before stun binding completed will trigger IPC socket layer to shutdown
19 * the connection.
20 *
21 * - PendingTCP: `connection_pending_` indicates whether there is an
22 * outstanding TCP connection in progress.
23 *
24 * - PretendWri: Tracked by `pretending_to_be_writable_`. Marking connection as
25 * WRITE_TIMEOUT will cause the connection be deleted. Instead, we're
26 * "pretending" we're still writable for a period of time such that reconnect
27 * could work.
28 *
29 * Data could only be sent in state 3. Sening data during state 2 & 6 will get
30 * EWOULDBLOCK, 4 & 5 EPIPE.
31 *
32 * OS Timeout 7 -------------+
33 * +----------------------->|Connected: N |
34 * | |Writable: N | Timeout
35 * | Timeout |Connection is |<----------------+
36 * | +------------------->|Dead | |
37 * | | +--------------+ |
38 * | | ^ |
39 * | | OnClose | |
40 * | | +-----------------------+ | |
41 * | | | | |Timeout |
42 * | | v | | |
43 * | 4 +----------+ 5 -----+--+--+ 6 -----+-----+
44 * | |Connected: N|Send() or |Connected: N| |Connected: Y|
45 * | |Writable: Y|Ping() |Writable: Y|OnConnect |Writable: Y|
46 * | |PendingTCP:N+--------> |PendingTCP:Y+---------> |PendingTCP:N|
47 * | |PretendWri:Y| |PretendWri:Y| |PretendWri:Y|
48 * | +-----+------+ +------------+ +---+--+-----+
49 * | ^ ^ | |
50 * | | | OnClose | |
51 * | | +----------------------------------------------+ |
52 * | | |
53 * | | Stun Binding Completed |
54 * | | |
55 * | | OnClose |
56 * | +------------------------------------------------+ |
57 * | | v
58 * 1 -----------+ 2 -----------+Stun 3 -----------+
59 * |Connected: N| |Connected: Y|Binding |Connected: Y|
60 * |Writable: N|OnConnect |Writable: N|Completed |Writable: Y|
61 * |PendingTCP:Y+---------> |PendingTCP:N+--------> |PendingTCP:N|
62 * |PretendWri:N| |PretendWri:N| |PretendWri:N|
63 * +------------+ +------------+ +------------+
64 *
65 */
66
67 #include "p2p/base/tcp_port.h"
68
69 #include <errno.h>
70
71 #include <utility>
72 #include <vector>
73
74 #include "absl/algorithm/container.h"
75 #include "absl/memory/memory.h"
76 #include "absl/strings/string_view.h"
77 #include "api/task_queue/pending_task_safety_flag.h"
78 #include "api/units/time_delta.h"
79 #include "p2p/base/p2p_constants.h"
80 #include "rtc_base/checks.h"
81 #include "rtc_base/ip_address.h"
82 #include "rtc_base/logging.h"
83 #include "rtc_base/net_helper.h"
84 #include "rtc_base/rate_tracker.h"
85 #include "rtc_base/third_party/sigslot/sigslot.h"
86
87 namespace cricket {
88 using ::webrtc::SafeTask;
89 using ::webrtc::TimeDelta;
90
TCPPort(rtc::Thread * thread,rtc::PacketSocketFactory * factory,const rtc::Network * network,uint16_t min_port,uint16_t max_port,absl::string_view username,absl::string_view password,bool allow_listen,const webrtc::FieldTrialsView * field_trials)91 TCPPort::TCPPort(rtc::Thread* thread,
92 rtc::PacketSocketFactory* factory,
93 const rtc::Network* network,
94 uint16_t min_port,
95 uint16_t max_port,
96 absl::string_view username,
97 absl::string_view password,
98 bool allow_listen,
99 const webrtc::FieldTrialsView* field_trials)
100 : Port(thread,
101 LOCAL_PORT_TYPE,
102 factory,
103 network,
104 min_port,
105 max_port,
106 username,
107 password,
108 field_trials),
109 allow_listen_(allow_listen),
110 error_(0) {
111 // TODO(mallinath) - Set preference value as per RFC 6544.
112 // http://b/issue?id=7141794
113 if (allow_listen_) {
114 TryCreateServerSocket();
115 }
116 // Set TCP_NODELAY (via OPT_NODELAY) for improved performance; this causes
117 // small media packets to be sent immediately rather than being buffered up,
118 // reducing latency.
119 SetOption(rtc::Socket::OPT_NODELAY, 1);
120 }
121
~TCPPort()122 TCPPort::~TCPPort() {
123 listen_socket_ = nullptr;
124 std::list<Incoming>::iterator it;
125 for (it = incoming_.begin(); it != incoming_.end(); ++it)
126 delete it->socket;
127 incoming_.clear();
128 }
129
CreateConnection(const Candidate & address,CandidateOrigin origin)130 Connection* TCPPort::CreateConnection(const Candidate& address,
131 CandidateOrigin origin) {
132 if (!SupportsProtocol(address.protocol())) {
133 return NULL;
134 }
135
136 if ((address.tcptype() == TCPTYPE_ACTIVE_STR &&
137 address.type() != PRFLX_PORT_TYPE) ||
138 (address.tcptype().empty() && address.address().port() == 0)) {
139 // It's active only candidate, we should not try to create connections
140 // for these candidates.
141 return NULL;
142 }
143
144 // We can't accept TCP connections incoming on other ports
145 if (origin == ORIGIN_OTHER_PORT)
146 return NULL;
147
148 // We don't know how to act as an ssl server yet
149 if ((address.protocol() == SSLTCP_PROTOCOL_NAME) &&
150 (origin == ORIGIN_THIS_PORT)) {
151 return NULL;
152 }
153
154 if (!IsCompatibleAddress(address.address())) {
155 return NULL;
156 }
157
158 TCPConnection* conn = NULL;
159 if (rtc::AsyncPacketSocket* socket = GetIncoming(address.address(), true)) {
160 // Incoming connection; we already created a socket and connected signals,
161 // so we need to hand off the "read packet" responsibility to
162 // TCPConnection.
163 socket->SignalReadPacket.disconnect(this);
164 conn = new TCPConnection(NewWeakPtr(), address, socket);
165 } else {
166 // Outgoing connection, which will create a new socket for which we still
167 // need to connect SignalReadyToSend and SignalSentPacket.
168 conn = new TCPConnection(NewWeakPtr(), address);
169 if (conn->socket()) {
170 conn->socket()->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
171 conn->socket()->SignalSentPacket.connect(this, &TCPPort::OnSentPacket);
172 }
173 }
174 AddOrReplaceConnection(conn);
175 return conn;
176 }
177
PrepareAddress()178 void TCPPort::PrepareAddress() {
179 if (listen_socket_) {
180 // Socket may be in the CLOSED state if Listen()
181 // failed, we still want to add the socket address.
182 RTC_LOG(LS_VERBOSE) << "Preparing TCP address, current state: "
183 << static_cast<int>(listen_socket_->GetState());
184 AddAddress(listen_socket_->GetLocalAddress(),
185 listen_socket_->GetLocalAddress(), rtc::SocketAddress(),
186 TCP_PROTOCOL_NAME, "", TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE,
187 ICE_TYPE_PREFERENCE_HOST_TCP, 0, "", true);
188 } else {
189 RTC_LOG(LS_INFO) << ToString()
190 << ": Not listening due to firewall restrictions.";
191 // Note: We still add the address, since otherwise the remote side won't
192 // recognize our incoming TCP connections. According to
193 // https://tools.ietf.org/html/rfc6544#section-4.5, for active candidate,
194 // the port must be set to the discard port, i.e. 9. We can't be 100% sure
195 // which IP address will actually be used, so GetBestIP is as good as we
196 // can do.
197 // TODO(deadbeef): We could do something like create a dummy socket just to
198 // see what IP we get. But that may be overkill.
199 AddAddress(rtc::SocketAddress(Network()->GetBestIP(), DISCARD_PORT),
200 rtc::SocketAddress(Network()->GetBestIP(), 0),
201 rtc::SocketAddress(), TCP_PROTOCOL_NAME, "", TCPTYPE_ACTIVE_STR,
202 LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP, 0, "", true);
203 }
204 }
205
SendTo(const void * data,size_t size,const rtc::SocketAddress & addr,const rtc::PacketOptions & options,bool payload)206 int TCPPort::SendTo(const void* data,
207 size_t size,
208 const rtc::SocketAddress& addr,
209 const rtc::PacketOptions& options,
210 bool payload) {
211 rtc::AsyncPacketSocket* socket = NULL;
212 TCPConnection* conn = static_cast<TCPConnection*>(GetConnection(addr));
213
214 // For Connection, this is the code path used by Ping() to establish
215 // WRITABLE. It has to send through the socket directly as TCPConnection::Send
216 // checks writability.
217 if (conn) {
218 if (!conn->connected()) {
219 conn->MaybeReconnect();
220 return SOCKET_ERROR;
221 }
222 socket = conn->socket();
223 if (!socket) {
224 // The failure to initialize should have been logged elsewhere,
225 // so this log is not important.
226 RTC_LOG(LS_INFO) << ToString()
227 << ": Attempted to send to an uninitialized socket: "
228 << addr.ToSensitiveString();
229 error_ = EHOSTUNREACH;
230 return SOCKET_ERROR;
231 }
232 } else {
233 socket = GetIncoming(addr);
234 if (!socket) {
235 RTC_LOG(LS_ERROR) << ToString()
236 << ": Attempted to send to an unknown destination: "
237 << addr.ToSensitiveString();
238 error_ = EHOSTUNREACH;
239 return SOCKET_ERROR;
240 }
241 }
242 rtc::PacketOptions modified_options(options);
243 CopyPortInformationToPacketInfo(&modified_options.info_signaled_after_sent);
244 int sent = socket->Send(data, size, modified_options);
245 if (sent < 0) {
246 error_ = socket->GetError();
247 // Error from this code path for a Connection (instead of from a bare
248 // socket) will not trigger reconnecting. In theory, this shouldn't matter
249 // as OnClose should always be called and set connected to false.
250 RTC_LOG(LS_ERROR) << ToString() << ": TCP send of " << size
251 << " bytes failed with error " << error_;
252 }
253 return sent;
254 }
255
GetOption(rtc::Socket::Option opt,int * value)256 int TCPPort::GetOption(rtc::Socket::Option opt, int* value) {
257 auto const& it = socket_options_.find(opt);
258 if (it == socket_options_.end()) {
259 return -1;
260 }
261 *value = it->second;
262 return 0;
263 }
264
SetOption(rtc::Socket::Option opt,int value)265 int TCPPort::SetOption(rtc::Socket::Option opt, int value) {
266 socket_options_[opt] = value;
267 return 0;
268 }
269
GetError()270 int TCPPort::GetError() {
271 return error_;
272 }
273
SupportsProtocol(absl::string_view protocol) const274 bool TCPPort::SupportsProtocol(absl::string_view protocol) const {
275 return protocol == TCP_PROTOCOL_NAME || protocol == SSLTCP_PROTOCOL_NAME;
276 }
277
GetProtocol() const278 ProtocolType TCPPort::GetProtocol() const {
279 return PROTO_TCP;
280 }
281
OnNewConnection(rtc::AsyncListenSocket * socket,rtc::AsyncPacketSocket * new_socket)282 void TCPPort::OnNewConnection(rtc::AsyncListenSocket* socket,
283 rtc::AsyncPacketSocket* new_socket) {
284 RTC_DCHECK_EQ(socket, listen_socket_.get());
285
286 for (const auto& option : socket_options_) {
287 new_socket->SetOption(option.first, option.second);
288 }
289 Incoming incoming;
290 incoming.addr = new_socket->GetRemoteAddress();
291 incoming.socket = new_socket;
292 incoming.socket->SignalReadPacket.connect(this, &TCPPort::OnReadPacket);
293 incoming.socket->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
294 incoming.socket->SignalSentPacket.connect(this, &TCPPort::OnSentPacket);
295
296 RTC_LOG(LS_VERBOSE) << ToString() << ": Accepted connection from "
297 << incoming.addr.ToSensitiveString();
298 incoming_.push_back(incoming);
299 }
300
TryCreateServerSocket()301 void TCPPort::TryCreateServerSocket() {
302 listen_socket_ = absl::WrapUnique(socket_factory()->CreateServerTcpSocket(
303 rtc::SocketAddress(Network()->GetBestIP(), 0), min_port(), max_port(),
304 false /* ssl */));
305 if (!listen_socket_) {
306 RTC_LOG(LS_WARNING)
307 << ToString()
308 << ": TCP server socket creation failed; continuing anyway.";
309 return;
310 }
311 listen_socket_->SignalNewConnection.connect(this, &TCPPort::OnNewConnection);
312 }
313
GetIncoming(const rtc::SocketAddress & addr,bool remove)314 rtc::AsyncPacketSocket* TCPPort::GetIncoming(const rtc::SocketAddress& addr,
315 bool remove) {
316 rtc::AsyncPacketSocket* socket = NULL;
317 for (std::list<Incoming>::iterator it = incoming_.begin();
318 it != incoming_.end(); ++it) {
319 if (it->addr == addr) {
320 socket = it->socket;
321 if (remove)
322 incoming_.erase(it);
323 break;
324 }
325 }
326 return socket;
327 }
328
OnReadPacket(rtc::AsyncPacketSocket * socket,const char * data,size_t size,const rtc::SocketAddress & remote_addr,const int64_t & packet_time_us)329 void TCPPort::OnReadPacket(rtc::AsyncPacketSocket* socket,
330 const char* data,
331 size_t size,
332 const rtc::SocketAddress& remote_addr,
333 const int64_t& packet_time_us) {
334 Port::OnReadPacket(data, size, remote_addr, PROTO_TCP);
335 }
336
OnSentPacket(rtc::AsyncPacketSocket * socket,const rtc::SentPacket & sent_packet)337 void TCPPort::OnSentPacket(rtc::AsyncPacketSocket* socket,
338 const rtc::SentPacket& sent_packet) {
339 PortInterface::SignalSentPacket(sent_packet);
340 }
341
OnReadyToSend(rtc::AsyncPacketSocket * socket)342 void TCPPort::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
343 Port::OnReadyToSend();
344 }
345
346 // TODO(qingsi): `CONNECTION_WRITE_CONNECT_TIMEOUT` is overriden by
347 // `ice_unwritable_timeout` in IceConfig when determining the writability state.
348 // Replace this constant with the config parameter assuming the default value if
349 // we decide it is also applicable here.
TCPConnection(rtc::WeakPtr<Port> tcp_port,const Candidate & candidate,rtc::AsyncPacketSocket * socket)350 TCPConnection::TCPConnection(rtc::WeakPtr<Port> tcp_port,
351 const Candidate& candidate,
352 rtc::AsyncPacketSocket* socket)
353 : Connection(std::move(tcp_port), 0, candidate),
354 socket_(socket),
355 error_(0),
356 outgoing_(socket == NULL),
357 connection_pending_(false),
358 pretending_to_be_writable_(false),
359 reconnection_timeout_(cricket::CONNECTION_WRITE_CONNECT_TIMEOUT) {
360 RTC_DCHECK_EQ(port()->GetProtocol(), PROTO_TCP); // Needs to be TCPPort.
361 if (outgoing_) {
362 CreateOutgoingTcpSocket();
363 } else {
364 // Incoming connections should match one of the network addresses. Same as
365 // what's being checked in OnConnect, but just DCHECKing here.
366 RTC_LOG(LS_VERBOSE) << ToString() << ": socket ipaddr: "
367 << socket_->GetLocalAddress().ToSensitiveString()
368 << ", port() Network:" << port()->Network()->ToString();
369 RTC_DCHECK(absl::c_any_of(
370 port_->Network()->GetIPs(), [this](const rtc::InterfaceAddress& addr) {
371 return socket_->GetLocalAddress().ipaddr() == addr;
372 }));
373 ConnectSocketSignals(socket);
374 }
375 }
376
~TCPConnection()377 TCPConnection::~TCPConnection() {
378 RTC_DCHECK_RUN_ON(network_thread_);
379 }
380
Send(const void * data,size_t size,const rtc::PacketOptions & options)381 int TCPConnection::Send(const void* data,
382 size_t size,
383 const rtc::PacketOptions& options) {
384 if (!socket_) {
385 error_ = ENOTCONN;
386 return SOCKET_ERROR;
387 }
388
389 // Sending after OnClose on active side will trigger a reconnect for a
390 // outgoing connection. Note that the write state is still WRITABLE as we want
391 // to spend a few seconds attempting a reconnect before saying we're
392 // unwritable.
393 if (!connected()) {
394 MaybeReconnect();
395 return SOCKET_ERROR;
396 }
397
398 // Note that this is important to put this after the previous check to give
399 // the connection a chance to reconnect.
400 if (pretending_to_be_writable_ || write_state() != STATE_WRITABLE) {
401 // TODO(?): Should STATE_WRITE_TIMEOUT return a non-blocking error?
402 error_ = ENOTCONN;
403 return SOCKET_ERROR;
404 }
405 stats_.sent_total_packets++;
406 rtc::PacketOptions modified_options(options);
407 tcp_port()->CopyPortInformationToPacketInfo(
408 &modified_options.info_signaled_after_sent);
409 int sent = socket_->Send(data, size, modified_options);
410 int64_t now = rtc::TimeMillis();
411 if (sent < 0) {
412 stats_.sent_discarded_packets++;
413 error_ = socket_->GetError();
414 } else {
415 send_rate_tracker_.AddSamplesAtTime(now, sent);
416 }
417 last_send_data_ = now;
418 return sent;
419 }
420
GetError()421 int TCPConnection::GetError() {
422 return error_;
423 }
424
OnConnectionRequestResponse(StunRequest * req,StunMessage * response)425 void TCPConnection::OnConnectionRequestResponse(StunRequest* req,
426 StunMessage* response) {
427 // Process the STUN response before we inform upper layer ready to send.
428 Connection::OnConnectionRequestResponse(req, response);
429
430 // If we're in the state of pretending to be writeable, we should inform the
431 // upper layer it's ready to send again as previous EWOULDLBLOCK from socket
432 // would have stopped the outgoing stream.
433 if (pretending_to_be_writable_) {
434 Connection::OnReadyToSend();
435 }
436 pretending_to_be_writable_ = false;
437 RTC_DCHECK(write_state() == STATE_WRITABLE);
438 }
439
OnConnect(rtc::AsyncPacketSocket * socket)440 void TCPConnection::OnConnect(rtc::AsyncPacketSocket* socket) {
441 RTC_DCHECK_EQ(socket, socket_.get());
442
443 if (!port_) {
444 RTC_LOG(LS_ERROR) << "TCPConnection: Port has been deleted.";
445 return;
446 }
447
448 // Do not use this port if the socket bound to an address not associated with
449 // the desired network interface. This is seen in Chrome, where TCP sockets
450 // cannot be given a binding address, and the platform is expected to pick
451 // the correct local address.
452 //
453 // However, there are two situations in which we allow the bound address to
454 // not be one of the addresses of the requested interface:
455 // 1. The bound address is the loopback address. This happens when a proxy
456 // forces TCP to bind to only the localhost address (see issue 3927).
457 // 2. The bound address is the "any address". This happens when
458 // multiple_routes is disabled (see issue 4780).
459 //
460 // Note that, aside from minor differences in log statements, this logic is
461 // identical to that in TurnPort.
462 const rtc::SocketAddress& socket_address = socket->GetLocalAddress();
463 if (absl::c_any_of(port_->Network()->GetIPs(),
464 [socket_address](const rtc::InterfaceAddress& addr) {
465 return socket_address.ipaddr() == addr;
466 })) {
467 RTC_LOG(LS_VERBOSE) << ToString() << ": Connection established to "
468 << socket->GetRemoteAddress().ToSensitiveString();
469 } else {
470 if (socket->GetLocalAddress().IsLoopbackIP()) {
471 RTC_LOG(LS_WARNING) << "Socket is bound to the address:"
472 << socket_address.ipaddr().ToSensitiveString()
473 << ", rather than an address associated with network:"
474 << port_->Network()->ToString()
475 << ". Still allowing it since it's localhost.";
476 } else if (IPIsAny(port_->Network()->GetBestIP())) {
477 RTC_LOG(LS_WARNING)
478 << "Socket is bound to the address:"
479 << socket_address.ipaddr().ToSensitiveString()
480 << ", rather than an address associated with network:"
481 << port_->Network()->ToString()
482 << ". Still allowing it since it's the 'any' address"
483 ", possibly caused by multiple_routes being disabled.";
484 } else {
485 RTC_LOG(LS_WARNING) << "Dropping connection as TCP socket bound to IP "
486 << socket_address.ipaddr().ToSensitiveString()
487 << ", rather than an address associated with network:"
488 << port_->Network()->ToString();
489 OnClose(socket, 0);
490 return;
491 }
492 }
493
494 // Connection is established successfully.
495 set_connected(true);
496 connection_pending_ = false;
497 }
498
OnClose(rtc::AsyncPacketSocket * socket,int error)499 void TCPConnection::OnClose(rtc::AsyncPacketSocket* socket, int error) {
500 RTC_DCHECK_EQ(socket, socket_.get());
501 RTC_LOG(LS_INFO) << ToString() << ": Connection closed with error " << error;
502
503 if (!port_) {
504 RTC_LOG(LS_ERROR) << "TCPConnection: Port has been deleted.";
505 return;
506 }
507
508 // Guard against the condition where IPC socket will call OnClose for every
509 // packet it can't send.
510 if (connected()) {
511 set_connected(false);
512
513 // Prevent the connection from being destroyed by redundant SignalClose
514 // events.
515 pretending_to_be_writable_ = true;
516
517 // If this connection can't become connected and writable again in 5
518 // seconds, it's time to tear this down. This is the case for the original
519 // TCP connection on passive side during a reconnect.
520 // We don't attempt reconnect right here. This is to avoid a case where the
521 // shutdown is intentional and reconnect is not necessary. We only reconnect
522 // when the connection is used to Send() or Ping().
523 network_thread()->PostDelayedTask(
524 SafeTask(network_safety_.flag(),
525 [this]() {
526 if (pretending_to_be_writable_) {
527 Destroy();
528 }
529 }),
530 TimeDelta::Millis(reconnection_timeout()));
531 } else if (!pretending_to_be_writable_) {
532 // OnClose could be called when the underneath socket times out during the
533 // initial connect() (i.e. `pretending_to_be_writable_` is false) . We have
534 // to manually destroy here as this connection, as never connected, will not
535 // be scheduled for ping to trigger destroy.
536 socket_->UnsubscribeClose(this);
537 port()->DestroyConnectionAsync(this);
538 }
539 }
540
MaybeReconnect()541 void TCPConnection::MaybeReconnect() {
542 // Only reconnect for an outgoing TCPConnection when OnClose was signaled and
543 // no outstanding reconnect is pending.
544 if (connected() || connection_pending_ || !outgoing_) {
545 return;
546 }
547
548 RTC_LOG(LS_INFO) << ToString()
549 << ": TCP Connection with remote is closed, "
550 "trying to reconnect";
551
552 CreateOutgoingTcpSocket();
553 error_ = EPIPE;
554 }
555
OnReadPacket(rtc::AsyncPacketSocket * socket,const char * data,size_t size,const rtc::SocketAddress & remote_addr,const int64_t & packet_time_us)556 void TCPConnection::OnReadPacket(rtc::AsyncPacketSocket* socket,
557 const char* data,
558 size_t size,
559 const rtc::SocketAddress& remote_addr,
560 const int64_t& packet_time_us) {
561 RTC_DCHECK_EQ(socket, socket_.get());
562 Connection::OnReadPacket(data, size, packet_time_us);
563 }
564
OnReadyToSend(rtc::AsyncPacketSocket * socket)565 void TCPConnection::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
566 RTC_DCHECK_EQ(socket, socket_.get());
567 Connection::OnReadyToSend();
568 }
569
CreateOutgoingTcpSocket()570 void TCPConnection::CreateOutgoingTcpSocket() {
571 RTC_DCHECK(outgoing_);
572 int opts = (remote_candidate().protocol() == SSLTCP_PROTOCOL_NAME)
573 ? rtc::PacketSocketFactory::OPT_TLS_FAKE
574 : 0;
575
576 if (socket_) {
577 socket_->UnsubscribeClose(this);
578 }
579
580 rtc::PacketSocketTcpOptions tcp_opts;
581 tcp_opts.opts = opts;
582 socket_.reset(port()->socket_factory()->CreateClientTcpSocket(
583 rtc::SocketAddress(port()->Network()->GetBestIP(), 0),
584 remote_candidate().address(), port()->proxy(), port()->user_agent(),
585 tcp_opts));
586 if (socket_) {
587 RTC_LOG(LS_VERBOSE) << ToString() << ": Connecting from "
588 << socket_->GetLocalAddress().ToSensitiveString()
589 << " to "
590 << remote_candidate().address().ToSensitiveString();
591 set_connected(false);
592 connection_pending_ = true;
593 ConnectSocketSignals(socket_.get());
594 } else {
595 RTC_LOG(LS_WARNING) << ToString() << ": Failed to create connection to "
596 << remote_candidate().address().ToSensitiveString();
597 set_state(IceCandidatePairState::FAILED);
598 // We can't FailAndPrune directly here. FailAndPrune and deletes all
599 // the StunRequests from the request_map_. And if this is in the stack
600 // of Connection::Ping(), we are still using the request.
601 // Unwind the stack and defer the FailAndPrune.
602 network_thread()->PostTask(
603 SafeTask(network_safety_.flag(), [this]() { FailAndPrune(); }));
604 }
605 }
606
ConnectSocketSignals(rtc::AsyncPacketSocket * socket)607 void TCPConnection::ConnectSocketSignals(rtc::AsyncPacketSocket* socket) {
608 if (outgoing_) {
609 socket->SignalConnect.connect(this, &TCPConnection::OnConnect);
610 }
611 socket->SignalReadPacket.connect(this, &TCPConnection::OnReadPacket);
612 socket->SignalReadyToSend.connect(this, &TCPConnection::OnReadyToSend);
613 socket->SubscribeClose(this, [this, safety = network_safety_.flag()](
614 rtc::AsyncPacketSocket* s, int err) {
615 if (safety->alive())
616 OnClose(s, err);
617 });
618 }
619
620 } // namespace cricket
621