1 /*
2  *  Copyright (c) 2020, The OpenThread Authors.
3  *  All rights reserved.
4  *
5  *  Redistribution and use in source and binary forms, with or without
6  *  modification, are permitted provided that the following conditions are met:
7  *  1. Redistributions of source code must retain the above copyright
8  *     notice, this list of conditions and the following disclaimer.
9  *  2. Redistributions in binary form must reproduce the above copyright
10  *     notice, this list of conditions and the following disclaimer in the
11  *     documentation and/or other materials provided with the distribution.
12  *  3. Neither the name of the copyright holder nor the
13  *     names of its contributors may be used to endorse or promote products
14  *     derived from this software without specific prior written permission.
15  *
16  *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17  *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20  *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26  *  POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 /**
30  * @file
31  *   This file implements OTNS utilities.
32  *
33  */
34 
35 #include "otns.hpp"
36 
37 #if (OPENTHREAD_MTD || OPENTHREAD_FTD) && OPENTHREAD_CONFIG_OTNS_ENABLE
38 
39 #include "common/debug.hpp"
40 #include "common/locator_getters.hpp"
41 #include "common/log.hpp"
42 
43 namespace ot {
44 namespace Utils {
45 
46 RegisterLogModule("Otns");
47 
48 const int kMaxStatusStringLength = 128;
49 
EmitShortAddress(uint16_t aShortAddress)50 void Otns::EmitShortAddress(uint16_t aShortAddress) { EmitStatus("rloc16=%d", aShortAddress); }
51 
EmitExtendedAddress(const Mac::ExtAddress & aExtAddress)52 void Otns::EmitExtendedAddress(const Mac::ExtAddress &aExtAddress)
53 {
54     Mac::ExtAddress revExtAddress;
55     revExtAddress.Set(aExtAddress.m8, Mac::ExtAddress::kReverseByteOrder);
56     EmitStatus("extaddr=%s", revExtAddress.ToString().AsCString());
57 }
58 
EmitPingRequest(const Ip6::Address & aPeerAddress,uint16_t aPingLength,uint32_t aTimestamp,uint8_t aHopLimit)59 void Otns::EmitPingRequest(const Ip6::Address &aPeerAddress,
60                            uint16_t            aPingLength,
61                            uint32_t            aTimestamp,
62                            uint8_t             aHopLimit)
63 {
64     OT_UNUSED_VARIABLE(aHopLimit);
65     EmitStatus("ping_request=%s,%d,%lu", aPeerAddress.ToString().AsCString(), aPingLength, aTimestamp);
66 }
67 
EmitPingReply(const Ip6::Address & aPeerAddress,uint16_t aPingLength,uint32_t aTimestamp,uint8_t aHopLimit)68 void Otns::EmitPingReply(const Ip6::Address &aPeerAddress, uint16_t aPingLength, uint32_t aTimestamp, uint8_t aHopLimit)
69 {
70     EmitStatus("ping_reply=%s,%u,%lu,%d", aPeerAddress.ToString().AsCString(), aPingLength, aTimestamp, aHopLimit);
71 }
72 
EmitStatus(const char * aFmt,...)73 void Otns::EmitStatus(const char *aFmt, ...)
74 {
75     char statusStr[kMaxStatusStringLength + 1];
76     int  n;
77 
78     va_list ap;
79     va_start(ap, aFmt);
80 
81     n = vsnprintf(statusStr, sizeof(statusStr), aFmt, ap);
82     OT_UNUSED_VARIABLE(n);
83     OT_ASSERT(n >= 0);
84 
85     va_end(ap);
86 
87     otPlatOtnsStatus(statusStr);
88 }
89 
HandleNotifierEvents(Events aEvents)90 void Otns::HandleNotifierEvents(Events aEvents)
91 {
92     if (aEvents.Contains(kEventThreadRoleChanged))
93     {
94         EmitStatus("role=%d", Get<Mle::Mle>().GetRole());
95     }
96 
97     if (aEvents.Contains(kEventThreadPartitionIdChanged))
98     {
99         EmitStatus("parid=%x", Get<Mle::Mle>().GetLeaderData().GetPartitionId());
100     }
101 
102 #if OPENTHREAD_CONFIG_JOINER_ENABLE
103     if (aEvents.Contains(kEventJoinerStateChanged))
104     {
105         EmitStatus("joiner_state=%d", Get<MeshCoP::Joiner>().GetState());
106     }
107 #endif
108 }
109 
EmitNeighborChange(NeighborTable::Event aEvent,const Neighbor & aNeighbor)110 void Otns::EmitNeighborChange(NeighborTable::Event aEvent, const Neighbor &aNeighbor)
111 {
112     switch (aEvent)
113     {
114     case NeighborTable::kRouterAdded:
115         EmitStatus("router_added=%s", aNeighbor.GetExtAddress().ToString().AsCString());
116         break;
117     case NeighborTable::kRouterRemoved:
118         EmitStatus("router_removed=%s", aNeighbor.GetExtAddress().ToString().AsCString());
119         break;
120     case NeighborTable::kChildAdded:
121         EmitStatus("child_added=%s", aNeighbor.GetExtAddress().ToString().AsCString());
122         break;
123     case NeighborTable::kChildRemoved:
124         EmitStatus("child_removed=%s", aNeighbor.GetExtAddress().ToString().AsCString());
125         break;
126     case NeighborTable::kChildModeChanged:
127         break;
128     }
129 }
130 
EmitTransmit(const Mac::TxFrame & aFrame)131 void Otns::EmitTransmit(const Mac::TxFrame &aFrame)
132 {
133     Mac::Address dst;
134     uint16_t     frameControlField = aFrame.GetFrameControlField();
135     uint8_t      channel           = aFrame.GetChannel();
136     uint8_t      sequence          = aFrame.GetSequence();
137 
138     IgnoreError(aFrame.GetDstAddr(dst));
139 
140     if (dst.IsShort())
141     {
142         EmitStatus("transmit=%d,%04x,%d,%04x", channel, frameControlField, sequence, dst.GetShort());
143     }
144     else if (dst.IsExtended())
145     {
146         EmitStatus("transmit=%d,%04x,%d,%s", channel, frameControlField, sequence, dst.ToString().AsCString());
147     }
148     else
149     {
150         EmitStatus("transmit=%d,%04x,%d", channel, frameControlField, sequence);
151     }
152 }
153 
EmitDeviceMode(Mle::DeviceMode aMode)154 void Otns::EmitDeviceMode(Mle::DeviceMode aMode)
155 {
156     EmitStatus("mode=%s%s%s", aMode.IsRxOnWhenIdle() ? "r" : "", aMode.IsFullThreadDevice() ? "d" : "",
157                (aMode.GetNetworkDataType() == NetworkData::kFullSet) ? "n" : "");
158 }
159 
EmitCoapSend(const Coap::Message & aMessage,const Ip6::MessageInfo & aMessageInfo)160 void Otns::EmitCoapSend(const Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo)
161 {
162     char  uriPath[Coap::Message::kMaxReceivedUriPath + 1];
163     Error error;
164 
165     SuccessOrExit(error = aMessage.ReadUriPathOptions(uriPath));
166 
167     EmitStatus("coap=send,%d,%d,%d,%s,%s,%d", aMessage.GetMessageId(), aMessage.GetType(), aMessage.GetCode(), uriPath,
168                aMessageInfo.GetPeerAddr().ToString().AsCString(), aMessageInfo.GetPeerPort());
169 
170 exit:
171     LogWarnOnError(error, "EmitCoapSend");
172 }
173 
EmitCoapReceive(const Coap::Message & aMessage,const Ip6::MessageInfo & aMessageInfo)174 void Otns::EmitCoapReceive(const Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo)
175 {
176     char  uriPath[Coap::Message::kMaxReceivedUriPath + 1];
177     Error error = kErrorNone;
178 
179     SuccessOrExit(error = aMessage.ReadUriPathOptions(uriPath));
180 
181     EmitStatus("coap=recv,%d,%d,%d,%s,%s,%d", aMessage.GetMessageId(), aMessage.GetType(), aMessage.GetCode(), uriPath,
182                aMessageInfo.GetPeerAddr().ToString().AsCString(), aMessageInfo.GetPeerPort());
183 exit:
184     LogWarnOnError(error, "EmitCoapReceive");
185 }
186 
EmitCoapSendFailure(Error aError,Coap::Message & aMessage,const Ip6::MessageInfo & aMessageInfo)187 void Otns::EmitCoapSendFailure(Error aError, Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo)
188 {
189     char  uriPath[Coap::Message::kMaxReceivedUriPath + 1];
190     Error error = kErrorNone;
191 
192     SuccessOrExit(error = aMessage.ReadUriPathOptions(uriPath));
193 
194     EmitStatus("coap=send_error,%d,%d,%d,%s,%s,%d,%s", aMessage.GetMessageId(), aMessage.GetType(), aMessage.GetCode(),
195                uriPath, aMessageInfo.GetPeerAddr().ToString().AsCString(), aMessageInfo.GetPeerPort(),
196                ErrorToString(aError));
197 exit:
198     LogWarnOnError(error, "EmitCoapSendFailure");
199 }
200 
201 } // namespace Utils
202 } // namespace ot
203 
204 #endif // (OPENTHREAD_MTD || OPENTHREAD_FTD) && OPENTHREAD_CONFIG_OTNS_ENABLE
205