8cd040addcf41fc109ec78e2870188d71fa35a2d
[platform/upstream/connectedhomeip.git] / src / transport / TransportMgr.cpp
1 /*
2  *
3  *    Copyright (c) 2020 Project CHIP Authors
4  *
5  *    Licensed under the Apache License, Version 2.0 (the "License");
6  *    you may not use this file except in compliance with the License.
7  *    You may obtain a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *    Unless required by applicable law or agreed to in writing, software
12  *    distributed under the License is distributed on an "AS IS" BASIS,
13  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *    See the License for the specific language governing permissions and
15  */
16
17 /**
18  * @file
19  *   This file implements a stateless TransportMgr, it will took a raw message
20  * buffer from transports, and then extract the message header without decode it.
21  * For secure messages, it will pass it to the SecureSessionMgr, and for unsecure
22  * messages (rendezvous messages), it will pass it to RendezvousSession.
23  *   When sending messages, it will encode the packet header, and pass it to the
24  * transports.
25  *   The whole process is fully stateless.
26  */
27
28 #include <transport/TransportMgr.h>
29
30 #include <transport/RendezvousSession.h>
31 #include <transport/SecureSessionMgr.h>
32 #include <transport/raw/Base.h>
33 #include <transport/raw/MessageHeader.h>
34 #include <transport/raw/PeerAddress.h>
35
36 namespace chip {
37
38 CHIP_ERROR TransportMgrBase::Init(Transport::Base * transport)
39 {
40     if (mTransport != nullptr)
41     {
42         return CHIP_ERROR_INCORRECT_STATE;
43     }
44     mTransport = transport;
45     mTransport->SetMessageReceiveHandler(HandleMessageReceived, this);
46     ChipLogDetail(Inet, "TransportMgr initialized");
47     return CHIP_NO_ERROR;
48 }
49
50 void TransportMgrBase::HandleMessageReceived(const PacketHeader & packetHeader, const Transport::PeerAddress & peerAddress,
51                                              System::PacketBufferHandle msg, TransportMgrBase * dispatcher)
52 {
53     TransportMgrDelegate * handler =
54         packetHeader.GetFlags().Has(Header::FlagValues::kSecure) ? dispatcher->mSecureSessionMgr : dispatcher->mRendezvous;
55     if (handler != nullptr)
56     {
57         handler->OnMessageReceived(packetHeader, peerAddress, std::move(msg));
58     }
59     else
60     {
61         char addrBuffer[Transport::PeerAddress::kMaxToStringSize];
62         peerAddress.ToString(addrBuffer, sizeof(addrBuffer));
63         ChipLogError(Inet, "%s message from %s is dropped since no corresponding handler is set in TransportMgr.",
64                      packetHeader.GetFlags().Has(Header::FlagValues::kSecure) ? "Encrypted" : "Unencrypted", addrBuffer);
65     }
66 }
67 } // namespace chip