Matter SDK Coverage Report
Current view: top level - transport/raw - TCP.cpp (source / functions) Coverage Total Hit
Test: SHA:db08debc068562b264a2df3a7f3a8cc1d0b3aba1 Lines: 80.8 % 328 265
Test Date: 2025-10-02 07:10:30 Functions: 87.9 % 33 29

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

Generated by: LCOV version 2.0-1