Line data Source code
1 : /*
2 : *
3 : * Copyright (c) 2020-2025 Project CHIP Authors
4 : * Copyright (c) 2013-2017 Nest Labs, Inc.
5 : * All rights reserved.
6 : *
7 : * Licensed under the Apache License, Version 2.0 (the "License");
8 : * you may not use this file except in compliance with the License.
9 : * You may obtain a copy of the License at
10 : *
11 : * http://www.apache.org/licenses/LICENSE-2.0
12 : *
13 : * Unless required by applicable law or agreed to in writing, software
14 : * distributed under the License is distributed on an "AS IS" BASIS,
15 : * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 : * See the License for the specific language governing permissions and
17 : * limitations under the License.
18 : */
19 :
20 : /**
21 : * @file
22 : * This file implements the CHIP Transport object that maintains TCP connections
23 : * to peers. Handles both establishing new connections and accepting peer connection
24 : * requests.
25 : */
26 : #include <transport/raw/TCP.h>
27 :
28 : #include <lib/core/CHIPEncoding.h>
29 : #include <lib/support/CodeUtils.h>
30 : #include <lib/support/logging/CHIPLogging.h>
31 : #include <transport/raw/MessageHeader.h>
32 :
33 : #include <inttypes.h>
34 : #include <limits>
35 :
36 : namespace chip {
37 : namespace Transport {
38 : namespace {
39 :
40 : using namespace chip::Encoding;
41 :
42 : // Packets start with a 32-bit size field.
43 : constexpr size_t kPacketSizeBytes = 4;
44 :
45 : static_assert(System::PacketBuffer::kLargeBufMaxSizeWithoutReserve <= UINT32_MAX, "Cast below could truncate the value");
46 : static_assert(System::PacketBuffer::kLargeBufMaxSizeWithoutReserve >= kPacketSizeBytes,
47 : "Large buffer allocation should be large enough to hold the length field");
48 :
49 : constexpr uint32_t kMaxTCPMessageSize =
50 : static_cast<uint32_t>(System::PacketBuffer::kLargeBufMaxSizeWithoutReserve - kPacketSizeBytes);
51 :
52 : constexpr int kListenBacklogSize = 2;
53 :
54 27 : CHIP_ERROR GetPeerAddress(Inet::TCPEndPoint & endPoint, PeerAddress & outAddr)
55 : {
56 : Inet::IPAddress ipAddress;
57 : uint16_t port;
58 27 : Inet::InterfaceId interfaceId;
59 27 : ReturnErrorOnFailure(endPoint.GetPeerInfo(&ipAddress, &port));
60 27 : ReturnErrorOnFailure(endPoint.GetInterfaceId(&interfaceId));
61 27 : outAddr = PeerAddress::TCP(ipAddress, port, interfaceId);
62 :
63 27 : return CHIP_NO_ERROR;
64 : }
65 :
66 : } // namespace
67 :
68 309 : TCPBase::~TCPBase() = default;
69 :
70 314 : void TCPBase::CloseActiveConnections()
71 : {
72 : // Nothing to do; we can't release as long as references are being held
73 1562 : for (size_t i = 0; i < mActiveConnectionsSize; i++)
74 : {
75 1248 : if (mActiveConnections[i].InUse())
76 : {
77 3 : CloseConnectionInternal(mActiveConnections[i], CHIP_NO_ERROR, SuppressCallback::Yes);
78 : }
79 : }
80 314 : }
81 :
82 27 : CHIP_ERROR TCPBase::Init(TcpListenParameters & params)
83 : {
84 27 : CHIP_ERROR err = CHIP_NO_ERROR;
85 :
86 27 : VerifyOrExit(mState == TCPState::kNotReady, err = CHIP_ERROR_INCORRECT_STATE);
87 :
88 27 : mEndpointType = params.GetAddressType();
89 :
90 : // Primary socket endpoint created to help get EndPointManager handle for creating multiple
91 : // connection endpoints at runtime.
92 27 : err = params.GetEndPointManager()->NewEndPoint(mListenSocket);
93 27 : SuccessOrExit(err);
94 :
95 27 : if (params.IsServerListenEnabled())
96 : {
97 50 : err = mListenSocket->Bind(params.GetAddressType(), Inet::IPAddress::Any, params.GetListenPort(),
98 25 : params.GetInterfaceId().IsPresent());
99 25 : SuccessOrExit(err);
100 :
101 25 : mListenSocket->mAppState = reinterpret_cast<void *>(this);
102 25 : mListenSocket->OnConnectionReceived = HandleIncomingConnection;
103 25 : mListenSocket->OnAcceptError = HandleAcceptError;
104 :
105 25 : err = mListenSocket->Listen(kListenBacklogSize);
106 25 : SuccessOrExit(err);
107 25 : ChipLogProgress(Inet, "TCP server listening on port %d for incoming connections", params.GetListenPort());
108 : }
109 :
110 27 : mState = TCPState::kInitialized;
111 :
112 27 : exit:
113 54 : if (err != CHIP_NO_ERROR)
114 : {
115 0 : ChipLogError(Inet, "Failed to initialize TCP transport: %" CHIP_ERROR_FORMAT, err.Format());
116 0 : mListenSocket.Release();
117 : }
118 :
119 27 : return err;
120 : }
121 :
122 314 : void TCPBase::Close()
123 : {
124 314 : mListenSocket.Release();
125 :
126 314 : CloseActiveConnections();
127 :
128 314 : mState = TCPState::kNotReady;
129 314 : }
130 :
131 51 : ActiveTCPConnectionState * TCPBase::AllocateConnection(const Inet::TCPEndPointHandle & endpoint, const PeerAddress & address)
132 : {
133 : // If a peer initiates a connection through HandleIncomingConnection but the connection is never claimed
134 : // in ProcessSingleMessage, we'll be left with a dangling ActiveTCPConnectionState which can be
135 : // reclaimed. Don't try to reclaim these connections unless we're out of space
136 51 : for (int reclaim = 0; reclaim < 2; reclaim++)
137 : {
138 68 : for (size_t i = 0; i < mActiveConnectionsSize; i++)
139 : {
140 68 : ActiveTCPConnectionState * activeConnection = &mActiveConnections[i];
141 68 : if (!activeConnection->InUse() && (activeConnection->GetReferenceCount() == 0))
142 : {
143 : // Update state for the active connection
144 89 : activeConnection->Init(endpoint, address, [this](auto & conn) { TCPDisconnect(conn, true); });
145 51 : return activeConnection;
146 : }
147 : }
148 :
149 : // Out of space; reclaim connections that were never claimed by ProcessSingleMessage
150 : // (i.e. that have a ref count of 0)
151 0 : for (size_t i = 0; i < mActiveConnectionsSize; i++)
152 : {
153 0 : ActiveTCPConnectionState * activeConnection = &mActiveConnections[i];
154 0 : if (!activeConnection->InUse() && (activeConnection->GetReferenceCount() != 0))
155 : {
156 : char addrStr[Transport::PeerAddress::kMaxToStringSize];
157 0 : activeConnection->mPeerAddr.ToString(addrStr);
158 0 : ChipLogError(Inet, "Leaked TCP connection %p to %s.", activeConnection, addrStr);
159 : // Try to notify callbacks in the hope that they release; the connection is no good
160 0 : CloseConnectionInternal(*activeConnection, CHIP_ERROR_CONNECTION_CLOSED_UNEXPECTEDLY, SuppressCallback::No);
161 : }
162 0 : ActiveTCPConnectionHandle releaseUnclaimed(activeConnection);
163 0 : }
164 : }
165 0 : return nullptr;
166 : }
167 :
168 : // Find an ActiveTCPConnectionState corresponding to a peer address
169 51 : ActiveTCPConnectionHandle TCPBase::FindInUseConnection(const PeerAddress & address)
170 : {
171 51 : if (address.GetTransportType() != Type::kTcp)
172 : {
173 0 : return nullptr;
174 : }
175 :
176 179 : for (size_t i = 0; i < mActiveConnectionsSize; i++)
177 : {
178 145 : auto & conn = mActiveConnections[i];
179 145 : if (!conn.InUse())
180 : {
181 128 : continue;
182 : }
183 :
184 17 : if (conn.mPeerAddr == address)
185 : {
186 : Inet::IPAddress addr;
187 : uint16_t port;
188 17 : if (conn.IsConnected())
189 : {
190 : // Failure to get peer information means the connection is bad; close it
191 7 : CHIP_ERROR err = conn.mEndPoint->GetPeerInfo(&addr, &port);
192 14 : if (err != CHIP_NO_ERROR)
193 : {
194 0 : CloseConnectionInternal(conn, err, SuppressCallback::No);
195 0 : return nullptr;
196 : }
197 : }
198 :
199 17 : return ActiveTCPConnectionHandle(&conn);
200 : }
201 : }
202 :
203 34 : return nullptr;
204 : }
205 :
206 : // Find the ActiveTCPConnectionState for a given TCPEndPoint
207 18 : ActiveTCPConnectionState * TCPBase::FindActiveConnection(const Inet::TCPEndPointHandle & endPoint)
208 : {
209 26 : for (size_t i = 0; i < mActiveConnectionsSize; i++)
210 : {
211 26 : if (mActiveConnections[i].mEndPoint == endPoint && mActiveConnections[i].IsConnected())
212 : {
213 18 : return &mActiveConnections[i];
214 : }
215 : }
216 0 : return nullptr;
217 : }
218 :
219 30 : ActiveTCPConnectionHandle TCPBase::FindInUseConnection(const Inet::TCPEndPoint & endPoint)
220 : {
221 37 : for (size_t i = 0; i < mActiveConnectionsSize; i++)
222 : {
223 37 : if (mActiveConnections[i].mEndPoint == endPoint)
224 : {
225 30 : return ActiveTCPConnectionHandle(&mActiveConnections[i]);
226 : }
227 : }
228 0 : return nullptr;
229 : }
230 :
231 14 : CHIP_ERROR TCPBase::PrepareBuffer(System::PacketBufferHandle & msgBuf)
232 : {
233 : // Sent buffer data format is:
234 : // - packet size as a uint32_t
235 : // - actual data
236 :
237 14 : VerifyOrReturnError(mState == TCPState::kInitialized, CHIP_ERROR_INCORRECT_STATE);
238 14 : VerifyOrReturnError(kPacketSizeBytes + msgBuf->DataLength() <= System::PacketBuffer::kLargeBufMaxSizeWithoutReserve,
239 : CHIP_ERROR_INVALID_ARGUMENT);
240 :
241 : static_assert(kPacketSizeBytes <= UINT16_MAX);
242 14 : VerifyOrReturnError(msgBuf->EnsureReservedSize(static_cast<uint16_t>(kPacketSizeBytes)), CHIP_ERROR_NO_MEMORY);
243 :
244 14 : msgBuf->SetStart(msgBuf->Start() - kPacketSizeBytes);
245 :
246 14 : uint8_t * output = msgBuf->Start();
247 14 : LittleEndian::Write32(output, static_cast<uint32_t>(msgBuf->DataLength() - kPacketSizeBytes));
248 :
249 14 : return CHIP_NO_ERROR;
250 : }
251 :
252 10 : CHIP_ERROR TCPBase::SendMessage(const Transport::PeerAddress & address, System::PacketBufferHandle && msgBuf)
253 : {
254 10 : VerifyOrReturnError(address.GetTransportType() == Type::kTcp, CHIP_ERROR_INVALID_ARGUMENT);
255 10 : ReturnErrorOnFailure(PrepareBuffer(msgBuf));
256 :
257 : // Must find a previously-established connection with an owning reference
258 10 : auto connection = FindInUseConnection(address);
259 10 : VerifyOrReturnError(!connection.IsNull(), CHIP_ERROR_INCORRECT_STATE);
260 10 : if (connection->IsConnected())
261 : {
262 2 : return connection->mEndPoint->Send(std::move(msgBuf));
263 : }
264 :
265 8 : return SendAfterConnect(connection, std::move(msgBuf));
266 10 : }
267 :
268 4 : CHIP_ERROR TCPBase::SendMessage(const ActiveTCPConnectionHandle & connection, System::PacketBufferHandle && msgBuf)
269 : {
270 4 : VerifyOrReturnError(!connection.IsNull(), CHIP_ERROR_INVALID_ARGUMENT);
271 4 : ReturnErrorOnFailure(PrepareBuffer(msgBuf));
272 :
273 4 : if (connection->IsConnected())
274 : {
275 4 : return connection->mEndPoint->Send(std::move(msgBuf));
276 : }
277 :
278 0 : return SendAfterConnect(connection, std::move(msgBuf));
279 : }
280 :
281 38 : CHIP_ERROR TCPBase::StartConnect(const PeerAddress & addr, Transport::AppTCPConnectionCallbackCtxt * appState,
282 : ActiveTCPConnectionHandle & outPeerConnState)
283 : {
284 : #if INET_CONFIG_ENABLE_TCP_ENDPOINT
285 38 : Inet::TCPEndPointHandle endPoint;
286 38 : outPeerConnState.Release();
287 38 : ReturnErrorOnFailure(mListenSocket->GetEndPointManager().NewEndPoint(endPoint));
288 :
289 38 : InitEndpoint(endPoint);
290 :
291 38 : ActiveTCPConnectionHandle activeConnection = FindInUseConnection(addr);
292 : // Re-use existing connection to peer if already connected
293 38 : if (!activeConnection.IsNull())
294 : {
295 4 : if (appState != nullptr)
296 : {
297 : // We do not support parallel attempts to connect to peer when setting appState
298 0 : VerifyOrReturnError(activeConnection->mConnectionState == TCPState::kConnected &&
299 : activeConnection->mAppState == nullptr,
300 : CHIP_ERROR_INCORRECT_STATE);
301 0 : activeConnection->mAppState = appState;
302 : }
303 4 : outPeerConnState = activeConnection;
304 :
305 4 : if (activeConnection->mConnectionState == TCPState::kConnected)
306 : {
307 2 : HandleConnectionAttemptComplete(activeConnection, CHIP_NO_ERROR);
308 : }
309 :
310 4 : return CHIP_NO_ERROR;
311 : }
312 :
313 34 : activeConnection = AllocateConnection(endPoint, addr);
314 34 : VerifyOrReturnError(!activeConnection.IsNull(), CHIP_ERROR_NO_MEMORY);
315 34 : activeConnection->mAppState = appState;
316 34 : activeConnection->mConnectionState = TCPState::kConnecting;
317 :
318 34 : mUsedEndPointCount++;
319 :
320 34 : ReturnErrorOnFailure(endPoint->Connect(addr.GetIPAddress(), addr.GetPort(), addr.GetInterface()));
321 :
322 : // Set the return value of the peer connection state to the allocated
323 : // connection.
324 22 : outPeerConnState = activeConnection;
325 :
326 22 : return CHIP_NO_ERROR;
327 : #else
328 : return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;
329 : #endif
330 38 : }
331 :
332 8 : CHIP_ERROR TCPBase::SendAfterConnect(const ActiveTCPConnectionHandle & existing, System::PacketBufferHandle && msg)
333 : {
334 : #if INET_CONFIG_ENABLE_TCP_ENDPOINT
335 8 : VerifyOrReturnError(!existing.IsNull(), CHIP_ERROR_INCORRECT_STATE);
336 8 : const PeerAddress & addr = existing->mPeerAddr;
337 :
338 : // This will initiate a connection to the specified peer
339 8 : bool alreadyConnecting = false;
340 :
341 : // Iterate through the ENTIRE array. If a pending packet for
342 : // the address already exists, this means a connection is pending and
343 : // does NOT need to be re-established.
344 8 : mPendingPackets.ForEachActiveObject([&](PendingPacket * pending) {
345 2 : if (pending->mPeerAddress == addr)
346 : {
347 : // same destination exists.
348 2 : alreadyConnecting = true;
349 2 : pending->mPacketBuffer->AddToEnd(std::move(msg));
350 2 : return Loop::Break;
351 : }
352 0 : return Loop::Continue;
353 : });
354 :
355 : // If already connecting, buffer was just enqueued for more sending
356 8 : if (alreadyConnecting)
357 : {
358 2 : return CHIP_NO_ERROR;
359 : }
360 :
361 : // enqueue the packet once the connection succeeds
362 6 : VerifyOrReturnError(mPendingPackets.CreateObject(addr, std::move(msg)) != nullptr, CHIP_ERROR_NO_MEMORY);
363 :
364 6 : return CHIP_NO_ERROR;
365 : #else
366 : return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;
367 : #endif
368 : }
369 :
370 18 : CHIP_ERROR TCPBase::ProcessReceivedBuffer(const Inet::TCPEndPointHandle & endPoint, const PeerAddress & peerAddress,
371 : System::PacketBufferHandle && buffer)
372 : {
373 18 : ActiveTCPConnectionState * state = FindActiveConnection(endPoint);
374 : // There must be a preceding TCPConnect to hold a reference to connection
375 18 : VerifyOrReturnError(state != nullptr, CHIP_ERROR_INTERNAL);
376 18 : state->mReceived.AddToEnd(std::move(buffer));
377 :
378 40 : while (!state->mReceived.IsNull())
379 : {
380 : uint8_t messageSizeBuf[kPacketSizeBytes];
381 24 : CHIP_ERROR err = state->mReceived->Read(messageSizeBuf);
382 48 : if (err == CHIP_ERROR_BUFFER_TOO_SMALL)
383 : {
384 : // We don't have enough data to read the message size. Wait until there's more.
385 0 : return CHIP_NO_ERROR;
386 : }
387 48 : if (err != CHIP_NO_ERROR)
388 : {
389 0 : return err;
390 : }
391 24 : uint32_t messageSize = LittleEndian::Get32(messageSizeBuf);
392 24 : if (messageSize > kMaxTCPMessageSize)
393 : {
394 : // Message is too big for this node to process. Disconnect from peer.
395 1 : ChipLogError(Inet, "Received TCP message of length %" PRIu32 " exceeds limit.", messageSize);
396 1 : CloseConnectionInternal(*state, CHIP_ERROR_MESSAGE_TOO_LONG, SuppressCallback::No);
397 :
398 1 : return CHIP_ERROR_MESSAGE_TOO_LONG;
399 : }
400 : // The subtraction will not underflow because we successfully read kPacketSizeBytes.
401 23 : if (messageSize > (state->mReceived->TotalLength() - kPacketSizeBytes))
402 : {
403 : // We have not yet received the complete message.
404 0 : return CHIP_NO_ERROR;
405 : }
406 :
407 23 : state->mReceived.Consume(kPacketSizeBytes);
408 :
409 23 : if (messageSize == 0)
410 : {
411 : // Zero-length messages are not valid Matter messages. Reject to
412 : // prevent attackers from holding TCP connection slots indefinitely.
413 1 : ChipLogError(Inet, "Received zero-length TCP message, closing connection.");
414 1 : return CHIP_ERROR_INVALID_MESSAGE_LENGTH;
415 : }
416 :
417 22 : ReturnErrorOnFailure(ProcessSingleMessage(peerAddress, *state, messageSize));
418 : }
419 :
420 16 : return CHIP_NO_ERROR;
421 : }
422 :
423 22 : CHIP_ERROR TCPBase::ProcessSingleMessage(const PeerAddress & peerAddress, ActiveTCPConnectionState & state, size_t messageSize)
424 : {
425 : // We enter with `state->mReceived` containing at least one full message, perhaps in a chain.
426 : // `state->mReceived->Start()` currently points to the message data.
427 : // On exit, `state->mReceived` will have had `messageSize` bytes consumed, no matter what.
428 22 : System::PacketBufferHandle message;
429 :
430 22 : if (state.mReceived->DataLength() == messageSize)
431 : {
432 : // In this case, the head packet buffer contains exactly the message.
433 : // This is common because typical messages fit in a network packet, and are delivered as such.
434 : // Peel off the head to pass upstream, which effectively consumes it from `state->mReceived`.
435 15 : message = state.mReceived.PopHead();
436 : }
437 : else
438 : {
439 : // The message is either longer or shorter than the head buffer.
440 : // In either case, copy the message to a fresh linear buffer to pass upstream. We always copy, rather than provide
441 : // a shared reference to the current buffer, in case upper layers manipulate the buffer in ways that would affect
442 : // our use, e.g. chaining it elsewhere or reusing space beyond the current message.
443 7 : message = System::PacketBufferHandle::New(messageSize, 0);
444 7 : if (message.IsNull())
445 : {
446 0 : return CHIP_ERROR_NO_MEMORY;
447 : }
448 7 : CHIP_ERROR err = state.mReceived->Read(message->Start(), messageSize);
449 7 : state.mReceived.Consume(messageSize);
450 7 : ReturnErrorOnFailure(err);
451 7 : message->SetDataLength(messageSize);
452 : }
453 :
454 22 : MessageTransportContext msgContext;
455 22 : msgContext.conn = &state; // Take ownership
456 22 : HandleMessageReceived(peerAddress, std::move(message), &msgContext);
457 22 : return CHIP_NO_ERROR;
458 22 : }
459 :
460 51 : void TCPBase::CloseConnectionInternal(ActiveTCPConnectionState & connection, CHIP_ERROR err, SuppressCallback suppressCallback)
461 : {
462 51 : if (connection.mConnectionState == TCPState::kClosed || !connection.mEndPoint)
463 : {
464 0 : return;
465 : }
466 : TCPState prevState;
467 : char addrStr[Transport::PeerAddress::kMaxToStringSize];
468 51 : connection.mPeerAddr.ToString(addrStr);
469 51 : ChipLogProgress(Inet, "Closing connection with peer %s.", addrStr);
470 :
471 51 : Inet::TCPEndPointHandle endpoint = connection.mEndPoint;
472 51 : connection.mEndPoint.Release();
473 102 : if (err == CHIP_NO_ERROR)
474 : {
475 3 : endpoint->Close();
476 : }
477 : else
478 : {
479 48 : endpoint->Abort();
480 : }
481 :
482 51 : prevState = connection.mConnectionState;
483 51 : connection.mConnectionState = TCPState::kClosed;
484 :
485 51 : if (suppressCallback == SuppressCallback::No)
486 : {
487 12 : if (prevState == TCPState::kConnecting)
488 : {
489 0 : ActiveTCPConnectionHandle holder(&connection);
490 : // Call upper layer connection attempt complete handler
491 0 : HandleConnectionAttemptComplete(holder, err);
492 0 : }
493 : else
494 : {
495 : // Call upper layer connection closed handler
496 12 : HandleConnectionClosed(connection, err);
497 : }
498 : }
499 :
500 51 : connection.Free();
501 51 : mUsedEndPointCount--;
502 51 : }
503 :
504 10 : CHIP_ERROR TCPBase::HandleTCPEndPointDataReceived(const Inet::TCPEndPointHandle & endPoint, System::PacketBufferHandle && buffer)
505 : {
506 10 : PeerAddress peerAddress;
507 10 : ReturnErrorOnFailure(GetPeerAddress(*endPoint, peerAddress));
508 :
509 10 : TCPBase * tcp = reinterpret_cast<TCPBase *>(endPoint->mAppState);
510 10 : CHIP_ERROR err = tcp->ProcessReceivedBuffer(endPoint, peerAddress, std::move(buffer));
511 :
512 20 : if (err != CHIP_NO_ERROR)
513 : {
514 : // Connection could need to be closed at this point
515 0 : ChipLogError(Inet, "Failed to accept received TCP message: %" CHIP_ERROR_FORMAT, err.Format());
516 0 : return CHIP_ERROR_UNEXPECTED_EVENT;
517 : }
518 10 : return CHIP_NO_ERROR;
519 : }
520 :
521 21 : void TCPBase::HandleTCPEndPointConnectComplete(const Inet::TCPEndPointHandle & endPoint, CHIP_ERROR conErr)
522 : {
523 21 : CHIP_ERROR err = CHIP_NO_ERROR;
524 21 : bool foundPendingPacket = false;
525 21 : TCPBase * tcp = reinterpret_cast<TCPBase *>(endPoint->mAppState);
526 21 : ActiveTCPConnectionHandle activeConnection;
527 :
528 21 : PeerAddress addr;
529 : char addrStr[Transport::PeerAddress::kMaxToStringSize];
530 21 : activeConnection = tcp->FindInUseConnection(*endPoint);
531 21 : if (activeConnection.IsNull())
532 : {
533 0 : err = GetPeerAddress(*endPoint, addr);
534 : }
535 : else
536 : {
537 21 : addr = activeConnection->mPeerAddr;
538 : }
539 42 : if (err == CHIP_NO_ERROR)
540 : {
541 21 : addr.ToString(addrStr);
542 : }
543 :
544 63 : if (conErr != CHIP_NO_ERROR || err != CHIP_NO_ERROR)
545 : {
546 0 : auto failure = (conErr != CHIP_NO_ERROR) ? conErr : err;
547 0 : if (!activeConnection.IsNull())
548 : {
549 0 : tcp->CloseConnectionInternal(*activeConnection, failure, SuppressCallback::No);
550 : }
551 0 : ChipLogError(Inet, "Connection establishment with %s encountered an error: %" CHIP_ERROR_FORMAT, addrStr, failure.Format());
552 0 : return;
553 : }
554 : // Set the Data received handler when connection completes
555 21 : endPoint->OnDataReceived = HandleTCPEndPointDataReceived;
556 21 : endPoint->OnDataSent = nullptr;
557 21 : endPoint->OnConnectionClosed = HandleTCPEndPointConnectionClosed;
558 :
559 21 : VerifyOrDie(!activeConnection.IsNull());
560 :
561 : // Set to Connected state
562 21 : activeConnection->mConnectionState = TCPState::kConnected;
563 :
564 : // Disable TCP Nagle buffering by setting TCP_NODELAY socket option to true.
565 : // This is to expedite transmission of payload data and not rely on the
566 : // network stack's configuration of collating enough data in the TCP
567 : // window to begin transmission.
568 21 : err = endPoint->EnableNoDelay();
569 42 : if (err != CHIP_NO_ERROR)
570 : {
571 0 : tcp->CloseConnectionInternal(*activeConnection, err, SuppressCallback::No);
572 0 : return;
573 : }
574 :
575 : // Send any pending packets that are queued for this connection
576 21 : tcp->mPendingPackets.ForEachActiveObject([&](PendingPacket * pending) {
577 6 : if (pending->mPeerAddress == addr)
578 : {
579 6 : foundPendingPacket = true;
580 6 : System::PacketBufferHandle buffer = std::move(pending->mPacketBuffer);
581 6 : tcp->mPendingPackets.ReleaseObject(pending);
582 :
583 18 : if ((conErr == CHIP_NO_ERROR) && (err == CHIP_NO_ERROR))
584 : {
585 : // TODO(gmarcosb): These errors are just swallowed; caller unaware their message is just dropped?
586 : // Likely just falls through to a timeout instead of fail-fast
587 6 : err = endPoint->Send(std::move(buffer));
588 : }
589 6 : }
590 6 : return Loop::Continue;
591 : });
592 :
593 : // Set the TCPKeepalive configurations on the established connection
594 42 : TEMPORARY_RETURN_IGNORED endPoint->EnableKeepAlive(activeConnection->mTCPKeepAliveIntervalSecs,
595 21 : activeConnection->mTCPMaxNumKeepAliveProbes);
596 :
597 21 : ChipLogProgress(Inet, "Connection established successfully with %s.", addrStr);
598 :
599 : // Let higher layer/delegate know that connection is successfully
600 : // established
601 21 : tcp->HandleConnectionAttemptComplete(activeConnection, CHIP_NO_ERROR);
602 21 : }
603 :
604 9 : void TCPBase::HandleTCPEndPointConnectionClosed(const Inet::TCPEndPointHandle & endPoint, CHIP_ERROR err)
605 : {
606 9 : TCPBase * tcp = reinterpret_cast<TCPBase *>(endPoint->mAppState);
607 9 : ActiveTCPConnectionHandle activeConnection = tcp->FindInUseConnection(*endPoint);
608 :
609 9 : if (activeConnection.IsNull())
610 : {
611 0 : return;
612 : }
613 :
614 18 : if (err == CHIP_NO_ERROR && activeConnection->IsConnected())
615 : {
616 2 : err = CHIP_ERROR_CONNECTION_CLOSED_UNEXPECTEDLY;
617 : }
618 :
619 9 : tcp->CloseConnectionInternal(*activeConnection, err, SuppressCallback::No);
620 9 : }
621 :
622 : // Handler for incoming connection requests from peer nodes
623 19 : void TCPBase::HandleIncomingConnection(const Inet::TCPEndPointHandle & listenEndPoint, const Inet::TCPEndPointHandle & endPoint,
624 : const Inet::IPAddress & peerAddress, uint16_t peerPort)
625 : {
626 19 : TCPBase * tcp = reinterpret_cast<TCPBase *>(listenEndPoint->mAppState);
627 19 : ReturnAndLogOnFailure(tcp->DoHandleIncomingConnection(listenEndPoint, endPoint, peerAddress, peerPort), Inet,
628 : "Failure accepting incoming connection");
629 : }
630 :
631 19 : CHIP_ERROR TCPBase::DoHandleIncomingConnection(const Inet::TCPEndPointHandle & listenEndPoint,
632 : const Inet::TCPEndPointHandle & endPoint, const Inet::IPAddress & peerAddress,
633 : uint16_t peerPort)
634 : {
635 : #if INET_CONFIG_TEST
636 19 : if (sForceFailureInDoHandleIncomingConnection)
637 : {
638 2 : return CHIP_ERROR_INTERNAL;
639 : }
640 : #endif
641 :
642 : // GetPeerAddress may fail if the client has already closed the connection, just drop it.
643 17 : PeerAddress addr;
644 17 : ReturnErrorOnFailure(GetPeerAddress(*endPoint, addr));
645 :
646 17 : ActiveTCPConnectionState * activeConnection = AllocateConnection(endPoint, addr);
647 17 : VerifyOrReturnError(activeConnection != nullptr, CHIP_ERROR_TOO_MANY_CONNECTIONS);
648 :
649 17 : auto connectionCleanup = ScopeExit([&]() { activeConnection->Free(); });
650 :
651 17 : endPoint->mAppState = this;
652 17 : endPoint->OnDataReceived = HandleTCPEndPointDataReceived;
653 17 : endPoint->OnDataSent = nullptr;
654 17 : endPoint->OnConnectionClosed = HandleTCPEndPointConnectionClosed;
655 :
656 : // By default, disable TCP Nagle buffering by setting TCP_NODELAY socket option to true
657 : // If it fails, we can still use the connection
658 17 : RETURN_SAFELY_IGNORED endPoint->EnableNoDelay();
659 :
660 17 : mUsedEndPointCount++;
661 17 : activeConnection->mConnectionState = TCPState::kConnected;
662 :
663 : // Set the TCPKeepalive configurations on the received connection
664 : // If it fails, we can still use the connection until it dies
665 17 : RETURN_SAFELY_IGNORED endPoint->EnableKeepAlive(activeConnection->mTCPKeepAliveIntervalSecs,
666 17 : activeConnection->mTCPMaxNumKeepAliveProbes);
667 :
668 : char addrStr[Transport::PeerAddress::kMaxToStringSize];
669 17 : peerAddress.ToString(addrStr);
670 17 : ChipLogProgress(Inet, "Incoming connection established with peer at %s.", addrStr);
671 :
672 : // Call the upper layer handler for incoming connection received.
673 17 : HandleConnectionReceived(*activeConnection);
674 :
675 17 : connectionCleanup.release();
676 :
677 17 : return CHIP_NO_ERROR;
678 17 : }
679 :
680 2 : void TCPBase::HandleAcceptError(const Inet::TCPEndPointHandle & listeningEndpoint, CHIP_ERROR err)
681 : {
682 2 : ChipLogError(Inet, "Accept error: %" CHIP_ERROR_FORMAT, err.Format());
683 2 : }
684 :
685 38 : CHIP_ERROR TCPBase::TCPConnect(const PeerAddress & address, Transport::AppTCPConnectionCallbackCtxt * appState,
686 : ActiveTCPConnectionHandle & outPeerConnState)
687 : {
688 38 : VerifyOrReturnError(mState == TCPState::kInitialized, CHIP_ERROR_INCORRECT_STATE);
689 :
690 : // Verify that PeerAddress AddressType is TCP
691 38 : VerifyOrReturnError(address.GetTransportType() == Transport::Type::kTcp, CHIP_ERROR_INVALID_ARGUMENT);
692 :
693 38 : VerifyOrReturnError(mUsedEndPointCount < mActiveConnectionsSize, CHIP_ERROR_NO_MEMORY);
694 :
695 : char addrStr[Transport::PeerAddress::kMaxToStringSize];
696 38 : address.ToString(addrStr);
697 38 : ChipLogProgress(Inet, "Connecting to peer %s.", addrStr);
698 :
699 38 : ReturnErrorOnFailure(StartConnect(address, appState, outPeerConnState));
700 :
701 26 : return CHIP_NO_ERROR;
702 : }
703 :
704 38 : void TCPBase::TCPDisconnect(ActiveTCPConnectionState & conn, bool shouldAbort)
705 : {
706 : // If there are still active references, we need to notify them of connection closure
707 38 : SuppressCallback suppressCallback = (conn.GetReferenceCount() > 0) ? SuppressCallback::No : SuppressCallback::Yes;
708 :
709 : // This call should be able to disconnect the connection either when it is
710 : // already established, or when it is being set up.
711 38 : if ((conn.IsConnected() && shouldAbort) || conn.IsConnecting())
712 : {
713 38 : CloseConnectionInternal(conn, CHIP_ERROR_CONNECTION_ABORTED, suppressCallback);
714 : }
715 :
716 38 : if (conn.IsConnected() && !shouldAbort)
717 : {
718 0 : CloseConnectionInternal(conn, CHIP_NO_ERROR, suppressCallback);
719 : }
720 38 : }
721 :
722 42 : bool TCPBase::HasActiveConnections() const
723 : {
724 178 : for (size_t i = 0; i < mActiveConnectionsSize; i++)
725 : {
726 144 : if (mActiveConnections[i].IsConnected())
727 : {
728 8 : return true;
729 : }
730 : }
731 :
732 34 : return false;
733 : }
734 :
735 38 : void TCPBase::InitEndpoint(const Inet::TCPEndPointHandle & endpoint)
736 : {
737 38 : endpoint->mAppState = reinterpret_cast<void *>(this);
738 38 : endpoint->OnConnectComplete = HandleTCPEndPointConnectComplete;
739 38 : endpoint->SetConnectTimeout(mConnectTimeout);
740 38 : }
741 :
742 : #if INET_CONFIG_TEST
743 : bool TCPBase::sForceFailureInDoHandleIncomingConnection = false;
744 : #endif
745 :
746 : } // namespace Transport
747 : } // namespace chip
|