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