1 /*
2  *  Copyright (c) 2019-2021, 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 platform for TREL using IPv6/UDP socket under POSIX.
32  */
33 
34 #include "openthread-posix-config.h"
35 
36 #include "platform-posix.h"
37 
38 #include <arpa/inet.h>
39 #include <assert.h>
40 #include <fcntl.h>
41 #include <netinet/in.h>
42 #include <sys/socket.h>
43 #include <unistd.h>
44 
45 #include <openthread/logging.h>
46 #include <openthread/openthread-system.h>
47 #include <openthread/platform/trel.h>
48 
49 #include "logger.hpp"
50 #include "radio_url.hpp"
51 #include "system.hpp"
52 #include "common/code_utils.hpp"
53 
54 #if OPENTHREAD_CONFIG_RADIO_LINK_TREL_ENABLE
55 
56 static constexpr uint16_t kMaxPacketSize = 1400; // The max size of a TREL packet.
57 
58 typedef struct TxPacket
59 {
60     struct TxPacket *mNext;
61     uint8_t          mBuffer[kMaxPacketSize];
62     uint16_t         mLength;
63     otSockAddr       mDestSockAddr;
64 } TxPacket;
65 
66 static uint8_t            sRxPacketBuffer[kMaxPacketSize];
67 static uint16_t           sRxPacketLength;
68 static TxPacket           sTxPacketPool[OPENTHREAD_POSIX_CONFIG_TREL_TX_PACKET_POOL_SIZE];
69 static TxPacket          *sFreeTxPacketHead;  // A singly linked list of free/available `TxPacket` from pool.
70 static TxPacket          *sTxPacketQueueTail; // A circular linked list for queued tx packets.
71 static otPlatTrelCounters sCounters;
72 
73 static char sInterfaceName[IFNAMSIZ + 1];
74 static bool sInitialized = false;
75 static bool sEnabled     = false;
76 static int  sSocket      = -1;
77 
78 static const char kLogModuleName[] = "Trel";
79 
LogCrit(const char * aFormat,...)80 static void LogCrit(const char *aFormat, ...)
81 {
82     va_list args;
83 
84     va_start(args, aFormat);
85     otLogPlatArgs(OT_LOG_LEVEL_CRIT, kLogModuleName, aFormat, args);
86     va_end(args);
87 }
88 
LogWarn(const char * aFormat,...)89 static void LogWarn(const char *aFormat, ...)
90 {
91     va_list args;
92 
93     va_start(args, aFormat);
94     otLogPlatArgs(OT_LOG_LEVEL_WARN, kLogModuleName, aFormat, args);
95     va_end(args);
96 }
97 
LogNote(const char * aFormat,...)98 static void LogNote(const char *aFormat, ...)
99 {
100     va_list args;
101 
102     va_start(args, aFormat);
103     otLogPlatArgs(OT_LOG_LEVEL_NOTE, kLogModuleName, aFormat, args);
104     va_end(args);
105 }
106 
LogInfo(const char * aFormat,...)107 static void LogInfo(const char *aFormat, ...)
108 {
109     va_list args;
110 
111     va_start(args, aFormat);
112     otLogPlatArgs(OT_LOG_LEVEL_INFO, kLogModuleName, aFormat, args);
113     va_end(args);
114 }
115 
LogDebg(const char * aFormat,...)116 static void LogDebg(const char *aFormat, ...)
117 {
118     va_list args;
119 
120     va_start(args, aFormat);
121     otLogPlatArgs(OT_LOG_LEVEL_DEBG, kLogModuleName, aFormat, args);
122     va_end(args);
123 }
124 
Ip6AddrToString(const void * aAddress)125 static const char *Ip6AddrToString(const void *aAddress)
126 {
127     static char string[INET6_ADDRSTRLEN];
128     return inet_ntop(AF_INET6, aAddress, string, sizeof(string));
129 }
130 
BufferToString(const uint8_t * aBuffer,uint16_t aLength)131 static const char *BufferToString(const uint8_t *aBuffer, uint16_t aLength)
132 {
133     const uint16_t kMaxWrite = 16;
134     static char    string[1600];
135 
136     uint16_t num = 0;
137     char    *cur = &string[0];
138     char    *end = &string[sizeof(string) - 1];
139 
140     cur += snprintf(cur, (uint16_t)(end - cur), "[(len:%d) ", aLength);
141     VerifyOrExit(cur < end);
142 
143     while (aLength-- && (num < kMaxWrite))
144     {
145         cur += snprintf(cur, (uint16_t)(end - cur), "%02x ", *aBuffer++);
146         VerifyOrExit(cur < end);
147 
148         num++;
149     }
150 
151     if (aLength != 0)
152     {
153         cur += snprintf(cur, (uint16_t)(end - cur), "... ");
154         VerifyOrExit(cur < end);
155     }
156 
157     *cur++ = ']';
158     VerifyOrExit(cur < end);
159 
160     *cur = '\0';
161 
162 exit:
163     *end = '\0';
164     return string;
165 }
166 
PrepareSocket(uint16_t & aUdpPort)167 static void PrepareSocket(uint16_t &aUdpPort)
168 {
169     int                 val;
170     struct sockaddr_in6 sockAddr;
171     socklen_t           sockLen;
172 
173     LogDebg("PrepareSocket()");
174 
175     sSocket = SocketWithCloseExec(AF_INET6, SOCK_DGRAM, 0, kSocketNonBlock);
176     VerifyOrDie(sSocket >= 0, OT_EXIT_ERROR_ERRNO);
177 
178     // Make the socket non-blocking to allow immediate tx attempt.
179     val = fcntl(sSocket, F_GETFL, 0);
180     VerifyOrDie(val != -1, OT_EXIT_ERROR_ERRNO);
181     val = val | O_NONBLOCK;
182     VerifyOrDie(fcntl(sSocket, F_SETFL, val) == 0, OT_EXIT_ERROR_ERRNO);
183 
184     // Bind the socket.
185 
186     memset(&sockAddr, 0, sizeof(sockAddr));
187     sockAddr.sin6_family = AF_INET6;
188     sockAddr.sin6_addr   = in6addr_any;
189     sockAddr.sin6_port   = OPENTHREAD_POSIX_CONFIG_TREL_UDP_PORT;
190 
191     if (bind(sSocket, (struct sockaddr *)&sockAddr, sizeof(sockAddr)) == -1)
192     {
193         LogCrit("Failed to bind socket");
194         DieNow(OT_EXIT_ERROR_ERRNO);
195     }
196 
197 #ifdef __linux__
198     // Bind to the TREL interface
199     if (setsockopt(sSocket, SOL_SOCKET, SO_BINDTODEVICE, sInterfaceName, strlen(sInterfaceName)) < 0)
200     {
201         LogCrit("Failed to bind socket to the interface %s", sInterfaceName);
202         DieNow(OT_EXIT_ERROR_ERRNO);
203     }
204 #endif
205 
206     sockLen = sizeof(sockAddr);
207 
208     if (getsockname(sSocket, (struct sockaddr *)&sockAddr, &sockLen) == -1)
209     {
210         LogCrit("Failed to get the socket name");
211         DieNow(OT_EXIT_ERROR_ERRNO);
212     }
213 
214     aUdpPort = ntohs(sockAddr.sin6_port);
215 }
216 
SendPacket(const uint8_t * aBuffer,uint16_t aLength,const otSockAddr * aDestSockAddr)217 static otError SendPacket(const uint8_t *aBuffer, uint16_t aLength, const otSockAddr *aDestSockAddr)
218 {
219     otError             error = OT_ERROR_NONE;
220     struct sockaddr_in6 sockAddr;
221     ssize_t             ret;
222 
223     VerifyOrExit(sSocket >= 0, error = OT_ERROR_INVALID_STATE);
224 
225     memset(&sockAddr, 0, sizeof(sockAddr));
226     sockAddr.sin6_family = AF_INET6;
227     sockAddr.sin6_port   = htons(aDestSockAddr->mPort);
228     memcpy(&sockAddr.sin6_addr, &aDestSockAddr->mAddress, sizeof(otIp6Address));
229 
230     ret = sendto(sSocket, aBuffer, aLength, 0, (struct sockaddr *)&sockAddr, sizeof(sockAddr));
231 
232     if (ret != aLength)
233     {
234         LogDebg("SendPacket() -- sendto() failed errno %d", errno);
235 
236         switch (errno)
237         {
238         case ENETUNREACH:
239         case ENETDOWN:
240         case EHOSTUNREACH:
241             error = OT_ERROR_ABORT;
242             break;
243 
244         default:
245             error = OT_ERROR_INVALID_STATE;
246         }
247     }
248     else
249     {
250         ++sCounters.mTxPackets;
251         sCounters.mTxBytes += aLength;
252     }
253 
254 exit:
255     LogDebg("SendPacket([%s]:%u) err:%s pkt:%s", Ip6AddrToString(&aDestSockAddr->mAddress), aDestSockAddr->mPort,
256             otThreadErrorToString(error), BufferToString(aBuffer, aLength));
257     if (error != OT_ERROR_NONE)
258     {
259         ++sCounters.mTxFailure;
260     }
261     return error;
262 }
263 
ReceivePacket(int aSocket,otInstance * aInstance)264 static void ReceivePacket(int aSocket, otInstance *aInstance)
265 {
266     struct sockaddr_in6 sockAddr;
267     socklen_t           sockAddrLen = sizeof(sockAddr);
268     ssize_t             ret;
269 
270     memset(&sockAddr, 0, sizeof(sockAddr));
271 
272     ret = recvfrom(aSocket, (char *)sRxPacketBuffer, sizeof(sRxPacketBuffer), 0, (struct sockaddr *)&sockAddr,
273                    &sockAddrLen);
274     VerifyOrDie(ret >= 0, OT_EXIT_ERROR_ERRNO);
275 
276     sRxPacketLength = (uint16_t)(ret);
277 
278     if (sRxPacketLength > sizeof(sRxPacketBuffer))
279     {
280         sRxPacketLength = sizeof(sRxPacketLength);
281     }
282 
283     LogDebg("ReceivePacket() - received from [%s]:%d, id:%d, pkt:%s", Ip6AddrToString(&sockAddr.sin6_addr),
284             ntohs(sockAddr.sin6_port), sockAddr.sin6_scope_id, BufferToString(sRxPacketBuffer, sRxPacketLength));
285 
286     if (sEnabled)
287     {
288         otSockAddr senderAddr;
289 
290         ++sCounters.mRxPackets;
291         sCounters.mRxBytes += sRxPacketLength;
292 
293         memcpy(&senderAddr.mAddress, &sockAddr.sin6_addr, sizeof(otIp6Address));
294         senderAddr.mPort = ntohs(sockAddr.sin6_port);
295 
296         otPlatTrelHandleReceived(aInstance, sRxPacketBuffer, sRxPacketLength, &senderAddr);
297     }
298 }
299 
InitPacketQueue(void)300 static void InitPacketQueue(void)
301 {
302     sTxPacketQueueTail = NULL;
303 
304     // Chain all the packets in pool in the free linked list.
305     sFreeTxPacketHead = NULL;
306 
307     for (uint16_t index = 0; index < OT_ARRAY_LENGTH(sTxPacketPool); index++)
308     {
309         TxPacket *packet = &sTxPacketPool[index];
310 
311         packet->mNext     = sFreeTxPacketHead;
312         sFreeTxPacketHead = packet;
313     }
314 }
315 
SendQueuedPackets(void)316 static void SendQueuedPackets(void)
317 {
318     while (sTxPacketQueueTail != NULL)
319     {
320         TxPacket *packet = sTxPacketQueueTail->mNext; // tail->mNext is the head of the list.
321 
322         if (SendPacket(packet->mBuffer, packet->mLength, &packet->mDestSockAddr) == OT_ERROR_INVALID_STATE)
323         {
324             LogDebg("SendQueuedPackets() - SendPacket() would block");
325             break;
326         }
327 
328         // Remove the `packet` from the packet queue (circular
329         // linked list).
330 
331         if (packet == sTxPacketQueueTail)
332         {
333             sTxPacketQueueTail = NULL;
334         }
335         else
336         {
337             sTxPacketQueueTail->mNext = packet->mNext;
338         }
339 
340         // Add the `packet` to the free packet singly linked list.
341 
342         packet->mNext     = sFreeTxPacketHead;
343         sFreeTxPacketHead = packet;
344     }
345 }
346 
EnqueuePacket(const uint8_t * aBuffer,uint16_t aLength,const otSockAddr * aDestSockAddr)347 static void EnqueuePacket(const uint8_t *aBuffer, uint16_t aLength, const otSockAddr *aDestSockAddr)
348 {
349     TxPacket *packet;
350 
351     // Allocate an available packet entry (from the free packet list)
352     // and copy the packet content into it.
353 
354     VerifyOrExit(sFreeTxPacketHead != NULL, LogWarn("EnqueuePacket failed, queue is full"));
355     packet            = sFreeTxPacketHead;
356     sFreeTxPacketHead = sFreeTxPacketHead->mNext;
357 
358     memcpy(packet->mBuffer, aBuffer, aLength);
359     packet->mLength       = aLength;
360     packet->mDestSockAddr = *aDestSockAddr;
361 
362     // Add packet to the tail of TxPacketQueue circular linked-list.
363 
364     if (sTxPacketQueueTail == NULL)
365     {
366         packet->mNext      = packet;
367         sTxPacketQueueTail = packet;
368     }
369     else
370     {
371         packet->mNext             = sTxPacketQueueTail->mNext;
372         sTxPacketQueueTail->mNext = packet;
373         sTxPacketQueueTail        = packet;
374     }
375 
376     LogDebg("EnqueuePacket([%s]:%u) - %s", Ip6AddrToString(&aDestSockAddr->mAddress), aDestSockAddr->mPort,
377             BufferToString(aBuffer, aLength));
378 
379 exit:
380     return;
381 }
382 
ResetCounters()383 static void ResetCounters() { memset(&sCounters, 0, sizeof(sCounters)); }
384 
385 //---------------------------------------------------------------------------------------------------------------------
386 // trelDnssd
387 //
388 // The functions below are tied to mDNS or DNS-SD library being used on
389 // a device and need to be implemented per project/platform. A weak empty
390 // implementation is provided here which describes the expected
391 // behavior. They need to be overridden during project/platform
392 // integration.
393 
trelDnssdInitialize(const char * aTrelNetif)394 OT_TOOL_WEAK void trelDnssdInitialize(const char *aTrelNetif)
395 {
396     // This function initialize the TREL DNS-SD module on the given
397     // TREL Network Interface.
398 
399     OT_UNUSED_VARIABLE(aTrelNetif);
400 }
401 
trelDnssdStartBrowse(void)402 OT_TOOL_WEAK void trelDnssdStartBrowse(void)
403 {
404     // This function initiates an ongoing DNS-SD browse on the service
405     // name "_trel._udp" within the local browsing domain to discover
406     // other devices supporting TREL. The ongoing browse will produce
407     // two different types of events: `add` events and `remove` events.
408     // When the browse is started, it should produce an `add` event for
409     // every TREL peer currently present on the network. Whenever a
410     // TREL peer goes offline, a "remove" event should be produced.
411     // `Remove` events are not guaranteed, however. When a TREL service
412     // instance is discovered, a new ongoing DNS-SD query for an AAAA
413     // record MUST be started on the hostname indicated in the SRV
414     // record of the discovered instance. If multiple host IPv6
415     // addressees are discovered for a peer, one with highest scope
416     // among all addresses MUST be reported (if there are multiple
417     // address at same scope, one must be selected randomly).
418     //
419     // The platform MUST signal back the discovered peer info using
420     // `otPlatTrelHandleDiscoveredPeerInfo()` callback. This callback
421     // MUST be invoked when a new peer is discovered, or when there is
422     // a change in an existing entry (e.g., new TXT record or new port
423     // number or new IPv6 address), or when the peer is removed.
424 }
425 
trelDnssdStopBrowse(void)426 OT_TOOL_WEAK void trelDnssdStopBrowse(void)
427 {
428     // This function stops the ongoing DNS-SD browse started from an
429     // earlier call to `trelDnssdStartBrowse()`.
430 }
431 
trelDnssdNotifyPeerSocketAddressDifference(const otSockAddr * aPeerSockAddr,const otSockAddr * aRxSockAddr)432 OT_TOOL_WEAK void trelDnssdNotifyPeerSocketAddressDifference(const otSockAddr *aPeerSockAddr,
433                                                              const otSockAddr *aRxSockAddr)
434 {
435     // Notifies platform that a TREL packet was received from a previously
436     // discovered peer with `aPeerSockAddr` now using a different socket
437     // address `aRxSockAddr` compared to the one reported earlier by DNS-SD
438     // using the `otPlatTrelHandleDiscoveredPeerInfo()` callback.
439     //
440     // Ideally the platform DNS-SD should detect changes to advertised port
441     // and addresses by peers, however, there are situations where this is
442     // not detected reliably. This function signals to that we received a
443     // packet from a peer with it using a different port or address. This can
444     // be used to restart/confirm the DNS-SD service/address resolution for
445     // the peer service and/or take any other relevant actions.
446 
447     OT_UNUSED_VARIABLE(aPeerSockAddr);
448     OT_UNUSED_VARIABLE(aRxSockAddr);
449 }
450 
trelDnssdRegisterService(uint16_t aPort,const uint8_t * aTxtData,uint8_t aTxtLength)451 OT_TOOL_WEAK void trelDnssdRegisterService(uint16_t aPort, const uint8_t *aTxtData, uint8_t aTxtLength)
452 {
453     // This function registers a new service to be advertised using
454     // DNS-SD.
455     //
456     // The service name is "_trel._udp". The platform should use its own
457     // hostname, which when combined with the service name and the
458     // local DNS-SD domain name will produce the full service instance
459     // name, for example "example-host._trel._udp.local.".
460     //
461     // The domain under which the service instance name appears will
462     // be 'local' for mDNS, and will be whatever domain is used for
463     // service registration in the case of a non-mDNS local DNS-SD
464     // service.
465     //
466     // A subsequent call to this function updates the previous service.
467     // It is used to update the TXT record data and/or the port
468     // number.
469     //
470     // The `aTxtData` buffer is not persisted after the return from this
471     // function. The platform layer MUST not keep the pointer and
472     // instead copy the content if needed.
473 
474     OT_UNUSED_VARIABLE(aPort);
475     OT_UNUSED_VARIABLE(aTxtData);
476     OT_UNUSED_VARIABLE(aTxtLength);
477 }
478 
trelDnssdRemoveService(void)479 OT_TOOL_WEAK void trelDnssdRemoveService(void)
480 {
481     // This function removes any previously registered "_trel._udp"
482     // service using `platTrelRegisterService()`. Device must stop
483     // advertising TREL service after this call.
484 }
485 
trelDnssdUpdateFdSet(otSysMainloopContext * aContext)486 OT_TOOL_WEAK void trelDnssdUpdateFdSet(otSysMainloopContext *aContext)
487 {
488     // This function can be used to update the file descriptor sets
489     // by DNS-SD layer (if needed).
490 
491     OT_UNUSED_VARIABLE(aContext);
492 }
493 
trelDnssdProcess(otInstance * aInstance,const otSysMainloopContext * aContext)494 OT_TOOL_WEAK void trelDnssdProcess(otInstance *aInstance, const otSysMainloopContext *aContext)
495 {
496     // This function performs processing by DNS-SD (if needed).
497 
498     OT_UNUSED_VARIABLE(aInstance);
499     OT_UNUSED_VARIABLE(aContext);
500 }
501 
502 //---------------------------------------------------------------------------------------------------------------------
503 // otPlatTrel
504 
otPlatTrelEnable(otInstance * aInstance,uint16_t * aUdpPort)505 void otPlatTrelEnable(otInstance *aInstance, uint16_t *aUdpPort)
506 {
507     OT_UNUSED_VARIABLE(aInstance);
508 
509     VerifyOrExit(!IsSystemDryRun());
510 
511     VerifyOrExit(sInitialized && !sEnabled);
512 
513     PrepareSocket(*aUdpPort);
514     trelDnssdStartBrowse();
515 
516     sEnabled = true;
517 
518 exit:
519     return;
520 }
521 
otPlatTrelDisable(otInstance * aInstance)522 void otPlatTrelDisable(otInstance *aInstance)
523 {
524     OT_UNUSED_VARIABLE(aInstance);
525 
526     VerifyOrExit(!IsSystemDryRun());
527 
528     VerifyOrExit(sInitialized && sEnabled);
529 
530     close(sSocket);
531     sSocket = -1;
532     trelDnssdStopBrowse();
533     trelDnssdRemoveService();
534     sEnabled = false;
535 
536 exit:
537     return;
538 }
539 
otPlatTrelSend(otInstance * aInstance,const uint8_t * aUdpPayload,uint16_t aUdpPayloadLen,const otSockAddr * aDestSockAddr)540 void otPlatTrelSend(otInstance       *aInstance,
541                     const uint8_t    *aUdpPayload,
542                     uint16_t          aUdpPayloadLen,
543                     const otSockAddr *aDestSockAddr)
544 {
545     OT_UNUSED_VARIABLE(aInstance);
546 
547     VerifyOrExit(!IsSystemDryRun());
548 
549     VerifyOrExit(sEnabled);
550 
551     assert(aUdpPayloadLen <= kMaxPacketSize);
552 
553     // We try to send the packet immediately. If it fails (e.g.,
554     // network is down) `SendPacket()` returns `OT_ERROR_ABORT`. If
555     // the send operation would block (e.g., socket is not yet ready
556     // or is out of buffer) we get `OT_ERROR_INVALID_STATE`. In that
557     // case we enqueue the packet to send it later when socket becomes
558     // ready.
559 
560     if ((sTxPacketQueueTail != NULL) ||
561         (SendPacket(aUdpPayload, aUdpPayloadLen, aDestSockAddr) == OT_ERROR_INVALID_STATE))
562     {
563         EnqueuePacket(aUdpPayload, aUdpPayloadLen, aDestSockAddr);
564     }
565 
566 exit:
567     return;
568 }
569 
otPlatTrelNotifyPeerSocketAddressDifference(otInstance * aInstance,const otSockAddr * aPeerSockAddr,const otSockAddr * aRxSockAddr)570 void otPlatTrelNotifyPeerSocketAddressDifference(otInstance       *aInstance,
571                                                  const otSockAddr *aPeerSockAddr,
572                                                  const otSockAddr *aRxSockAddr)
573 {
574     OT_UNUSED_VARIABLE(aInstance);
575 
576     trelDnssdNotifyPeerSocketAddressDifference(aPeerSockAddr, aRxSockAddr);
577 }
578 
otPlatTrelRegisterService(otInstance * aInstance,uint16_t aPort,const uint8_t * aTxtData,uint8_t aTxtLength)579 void otPlatTrelRegisterService(otInstance *aInstance, uint16_t aPort, const uint8_t *aTxtData, uint8_t aTxtLength)
580 {
581     OT_UNUSED_VARIABLE(aInstance);
582     VerifyOrExit(!IsSystemDryRun());
583 
584     VerifyOrExit(sEnabled);
585 
586     trelDnssdRegisterService(aPort, aTxtData, aTxtLength);
587 
588 exit:
589     return;
590 }
591 
592 // We keep counters at the platform layer because TREL failures can only be captured accurately within
593 // the platform layer as the platform sometimes only queues the packet and the packet will be sent later
594 // and the error is only known after sent.
otPlatTrelGetCounters(otInstance * aInstance)595 const otPlatTrelCounters *otPlatTrelGetCounters(otInstance *aInstance)
596 {
597     OT_UNUSED_VARIABLE(aInstance);
598     return &sCounters;
599 }
600 
otPlatTrelResetCounters(otInstance * aInstance)601 void otPlatTrelResetCounters(otInstance *aInstance)
602 {
603     OT_UNUSED_VARIABLE(aInstance);
604     ResetCounters();
605 }
606 
otSysTrelInit(const char * aInterfaceName)607 void otSysTrelInit(const char *aInterfaceName)
608 {
609     // To silence "unused function" warning.
610     (void)LogCrit;
611     (void)LogWarn;
612     (void)LogInfo;
613     (void)LogNote;
614     (void)LogDebg;
615 
616     LogDebg("otSysTrelInit(aInterfaceName:\"%s\")", aInterfaceName != nullptr ? aInterfaceName : "");
617 
618     VerifyOrExit(!sInitialized && !sEnabled && aInterfaceName != nullptr);
619 
620     strncpy(sInterfaceName, aInterfaceName, sizeof(sInterfaceName) - 1);
621     sInterfaceName[sizeof(sInterfaceName) - 1] = '\0';
622 
623     trelDnssdInitialize(sInterfaceName);
624 
625     InitPacketQueue();
626     sInitialized = true;
627 
628     ResetCounters();
629 
630 exit:
631     return;
632 }
633 
otSysTrelDeinit(void)634 void otSysTrelDeinit(void) { platformTrelDeinit(); }
635 
636 //---------------------------------------------------------------------------------------------------------------------
637 // platformTrel system
638 
platformTrelInit(const char * aTrelUrl)639 void platformTrelInit(const char *aTrelUrl)
640 {
641     LogDebg("platformTrelInit(aTrelUrl:\"%s\")", aTrelUrl != nullptr ? aTrelUrl : "");
642 
643     if (aTrelUrl != nullptr)
644     {
645         ot::Posix::RadioUrl url(aTrelUrl);
646 
647         otSysTrelInit(url.GetPath());
648     }
649 }
650 
platformTrelDeinit(void)651 void platformTrelDeinit(void)
652 {
653     VerifyOrExit(sInitialized && !sEnabled);
654 
655     sInterfaceName[0] = '\0';
656     sInitialized      = false;
657     LogDebg("platformTrelDeinit()");
658 
659 exit:
660     return;
661 }
662 
platformTrelUpdateFdSet(otSysMainloopContext * aContext)663 void platformTrelUpdateFdSet(otSysMainloopContext *aContext)
664 {
665     assert(aContext != nullptr);
666 
667     VerifyOrExit(sEnabled);
668 
669     FD_SET(sSocket, &aContext->mReadFdSet);
670 
671     if (sTxPacketQueueTail != nullptr)
672     {
673         FD_SET(sSocket, &aContext->mWriteFdSet);
674     }
675 
676     if (aContext->mMaxFd < sSocket)
677     {
678         aContext->mMaxFd = sSocket;
679     }
680 
681     trelDnssdUpdateFdSet(aContext);
682 
683 exit:
684     return;
685 }
686 
platformTrelProcess(otInstance * aInstance,const otSysMainloopContext * aContext)687 void platformTrelProcess(otInstance *aInstance, const otSysMainloopContext *aContext)
688 {
689     VerifyOrExit(sEnabled);
690 
691     if (FD_ISSET(sSocket, &aContext->mWriteFdSet))
692     {
693         SendQueuedPackets();
694     }
695 
696     if (FD_ISSET(sSocket, &aContext->mReadFdSet))
697     {
698         ReceivePacket(sSocket, aInstance);
699     }
700 
701     trelDnssdProcess(aInstance, aContext);
702 
703 exit:
704     return;
705 }
706 
707 #endif // #if OPENTHREAD_CONFIG_RADIO_LINK_TREL_ENABLE
708