xref: /aosp_15_r20/external/openthread/src/posix/platform/udp.cpp (revision cfb92d1480a9e65faed56933e9c12405f45898b4)
1 /*
2  *  Copyright (c) 2018, 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  * @brief
32  *   This file includes the platform UDP driver.
33  */
34 
35 #ifdef __APPLE__
36 #define __APPLE_USE_RFC_3542
37 #endif
38 
39 #include "openthread-posix-config.h"
40 #include "platform-posix.h"
41 
42 #include <arpa/inet.h>
43 #include <assert.h>
44 #include <net/if.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <sys/select.h>
49 #include <unistd.h>
50 
51 #include <openthread/udp.h>
52 #include <openthread/platform/udp.h>
53 
54 #include "common/code_utils.hpp"
55 
56 #if OPENTHREAD_CONFIG_PLATFORM_UDP_ENABLE
57 
58 #include "posix/platform/ip6_utils.hpp"
59 #include "posix/platform/mainloop.hpp"
60 #include "posix/platform/udp.hpp"
61 
62 using namespace ot::Posix::Ip6Utils;
63 
64 namespace {
65 
66 constexpr size_t kMaxUdpSize = 1280;
67 
FdToHandle(int aFd)68 void *FdToHandle(int aFd) { return reinterpret_cast<void *>(aFd); }
69 
FdFromHandle(void * aHandle)70 int FdFromHandle(void *aHandle) { return static_cast<int>(reinterpret_cast<long>(aHandle)); }
71 
transmitPacket(int aFd,uint8_t * aPayload,uint16_t aLength,const otMessageInfo & aMessageInfo)72 otError transmitPacket(int aFd, uint8_t *aPayload, uint16_t aLength, const otMessageInfo &aMessageInfo)
73 {
74 #ifdef __APPLE__
75     // use fixed value for CMSG_SPACE is not a constant expression on macOS
76     constexpr size_t kBufferSize = 128;
77 #else
78     constexpr size_t kBufferSize = CMSG_SPACE(sizeof(struct in6_pktinfo)) + CMSG_SPACE(sizeof(int));
79 #endif
80     struct sockaddr_in6 peerAddr;
81     uint8_t             control[kBufferSize];
82     size_t              controlLength = 0;
83     struct iovec        iov;
84     struct msghdr       msg;
85     struct cmsghdr     *cmsg;
86     ssize_t             rval;
87     otError             error = OT_ERROR_NONE;
88 
89     memset(&peerAddr, 0, sizeof(peerAddr));
90     peerAddr.sin6_port   = htons(aMessageInfo.mPeerPort);
91     peerAddr.sin6_family = AF_INET6;
92     CopyIp6AddressTo(aMessageInfo.mPeerAddr, &peerAddr.sin6_addr);
93 
94     if (IsIp6AddressLinkLocal(aMessageInfo.mPeerAddr) && !aMessageInfo.mIsHostInterface)
95     {
96         // sin6_scope_id only works for link local destinations
97         peerAddr.sin6_scope_id = gNetifIndex;
98     }
99 
100     memset(control, 0, sizeof(control));
101 
102     iov.iov_base = aPayload;
103     iov.iov_len  = aLength;
104 
105     msg.msg_name       = &peerAddr;
106     msg.msg_namelen    = sizeof(peerAddr);
107     msg.msg_control    = control;
108     msg.msg_controllen = static_cast<decltype(msg.msg_controllen)>(sizeof(control));
109     msg.msg_iov        = &iov;
110     msg.msg_iovlen     = 1;
111     msg.msg_flags      = 0;
112 
113     {
114         int hopLimit = (aMessageInfo.mHopLimit ? aMessageInfo.mHopLimit : OPENTHREAD_CONFIG_IP6_HOP_LIMIT_DEFAULT);
115 
116         cmsg             = CMSG_FIRSTHDR(&msg);
117         cmsg->cmsg_level = IPPROTO_IPV6;
118         cmsg->cmsg_type  = IPV6_HOPLIMIT;
119         cmsg->cmsg_len   = CMSG_LEN(sizeof(int));
120 
121         memcpy(CMSG_DATA(cmsg), &hopLimit, sizeof(int));
122 
123         controlLength += CMSG_SPACE(sizeof(int));
124     }
125 
126     if (!IsIp6AddressMulticast(aMessageInfo.mSockAddr) && !IsIp6AddressUnspecified(aMessageInfo.mSockAddr))
127     {
128         struct in6_pktinfo pktinfo;
129 
130         cmsg             = CMSG_NXTHDR(&msg, cmsg);
131         cmsg->cmsg_level = IPPROTO_IPV6;
132         cmsg->cmsg_type  = IPV6_PKTINFO;
133         cmsg->cmsg_len   = CMSG_LEN(sizeof(pktinfo));
134 
135         pktinfo.ipi6_ifindex = aMessageInfo.mIsHostInterface ? 0 : gNetifIndex;
136 
137         CopyIp6AddressTo(aMessageInfo.mSockAddr, &pktinfo.ipi6_addr);
138         memcpy(CMSG_DATA(cmsg), &pktinfo, sizeof(pktinfo));
139 
140         controlLength += CMSG_SPACE(sizeof(pktinfo));
141     }
142 
143 #ifdef __APPLE__
144     msg.msg_controllen = static_cast<socklen_t>(controlLength);
145 #else
146     msg.msg_controllen           = controlLength;
147 #endif
148 
149     rval = sendmsg(aFd, &msg, 0);
150     VerifyOrExit(rval > 0, perror("sendmsg"));
151 
152 exit:
153     // EINVAL happens when we shift from child to router and the
154     // interface address changes. Ask callers to try again later.
155     if (rval == -1)
156     {
157         error = (errno == EINVAL) ? OT_ERROR_INVALID_STATE : OT_ERROR_FAILED;
158     }
159 
160     return error;
161 }
162 
receivePacket(int aFd,uint8_t * aPayload,uint16_t & aLength,otMessageInfo & aMessageInfo)163 otError receivePacket(int aFd, uint8_t *aPayload, uint16_t &aLength, otMessageInfo &aMessageInfo)
164 {
165     struct sockaddr_in6 peerAddr;
166     uint8_t             control[kMaxUdpSize];
167     struct iovec        iov;
168     struct msghdr       msg;
169     ssize_t             rval;
170 
171     iov.iov_base = aPayload;
172     iov.iov_len  = aLength;
173 
174     msg.msg_name       = &peerAddr;
175     msg.msg_namelen    = sizeof(peerAddr);
176     msg.msg_control    = control;
177     msg.msg_controllen = sizeof(control);
178     msg.msg_iov        = &iov;
179     msg.msg_iovlen     = 1;
180     msg.msg_flags      = 0;
181 
182     rval = recvmsg(aFd, &msg, 0);
183     VerifyOrExit(rval > 0, perror("recvmsg"));
184     aLength = static_cast<uint16_t>(rval);
185 
186     for (struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); cmsg != nullptr; cmsg = CMSG_NXTHDR(&msg, cmsg))
187     {
188         if (cmsg->cmsg_level == IPPROTO_IPV6)
189         {
190             if (cmsg->cmsg_type == IPV6_HOPLIMIT)
191             {
192                 int hoplimit;
193 
194                 memcpy(&hoplimit, CMSG_DATA(cmsg), sizeof(hoplimit));
195                 aMessageInfo.mHopLimit = static_cast<uint8_t>(hoplimit);
196             }
197             else if (cmsg->cmsg_type == IPV6_PKTINFO)
198             {
199                 struct in6_pktinfo pktinfo;
200 
201                 memcpy(&pktinfo, CMSG_DATA(cmsg), sizeof(pktinfo));
202 
203                 aMessageInfo.mIsHostInterface = (pktinfo.ipi6_ifindex != gNetifIndex);
204                 ReadIp6AddressFrom(&pktinfo.ipi6_addr, aMessageInfo.mSockAddr);
205             }
206         }
207     }
208 
209     aMessageInfo.mPeerPort = ntohs(peerAddr.sin6_port);
210     ReadIp6AddressFrom(&peerAddr.sin6_addr, aMessageInfo.mPeerAddr);
211 
212 exit:
213     return rval > 0 ? OT_ERROR_NONE : OT_ERROR_FAILED;
214 }
215 
216 } // namespace
217 
otPlatUdpSocket(otUdpSocket * aUdpSocket)218 otError otPlatUdpSocket(otUdpSocket *aUdpSocket)
219 {
220     otError error = OT_ERROR_NONE;
221     int     fd;
222 
223     assert(aUdpSocket->mHandle == nullptr);
224 
225     fd = SocketWithCloseExec(AF_INET6, SOCK_DGRAM, IPPROTO_UDP, kSocketNonBlock);
226     VerifyOrExit(fd >= 0, error = OT_ERROR_FAILED);
227 
228     aUdpSocket->mHandle = FdToHandle(fd);
229 
230 exit:
231     return error;
232 }
233 
otPlatUdpClose(otUdpSocket * aUdpSocket)234 otError otPlatUdpClose(otUdpSocket *aUdpSocket)
235 {
236     otError error = OT_ERROR_NONE;
237     int     fd;
238 
239     // Only call `close()` on platform UDP sockets.
240     // Platform UDP sockets always have valid `mHandle` upon creation.
241     VerifyOrExit(aUdpSocket->mHandle != nullptr);
242 
243     fd = FdFromHandle(aUdpSocket->mHandle);
244     VerifyOrExit(0 == close(fd), error = OT_ERROR_FAILED);
245 
246     aUdpSocket->mHandle = nullptr;
247 
248 exit:
249     return error;
250 }
251 
otPlatUdpBind(otUdpSocket * aUdpSocket)252 otError otPlatUdpBind(otUdpSocket *aUdpSocket)
253 {
254     otError error = OT_ERROR_NONE;
255     int     fd;
256 
257     assert(gNetifIndex != 0);
258     assert(aUdpSocket->mHandle != nullptr);
259     VerifyOrExit(aUdpSocket->mSockName.mPort != 0, error = OT_ERROR_INVALID_ARGS);
260     fd = FdFromHandle(aUdpSocket->mHandle);
261 
262     {
263         struct sockaddr_in6 sin6;
264 
265         memset(&sin6, 0, sizeof(struct sockaddr_in6));
266         sin6.sin6_port   = htons(aUdpSocket->mSockName.mPort);
267         sin6.sin6_family = AF_INET6;
268         CopyIp6AddressTo(aUdpSocket->mSockName.mAddress, &sin6.sin6_addr);
269 
270         VerifyOrExit(0 == bind(fd, reinterpret_cast<struct sockaddr *>(&sin6), sizeof(sin6)), error = OT_ERROR_FAILED);
271     }
272 
273     {
274         int on = 1;
275         VerifyOrExit(0 == setsockopt(fd, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &on, sizeof(on)), error = OT_ERROR_FAILED);
276         VerifyOrExit(0 == setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof(on)), error = OT_ERROR_FAILED);
277     }
278 
279 exit:
280     if (error == OT_ERROR_FAILED)
281     {
282         ot::Posix::Udp::LogCrit("Failed to bind UDP socket: %s", strerror(errno));
283     }
284 
285     return error;
286 }
287 
otPlatUdpBindToNetif(otUdpSocket * aUdpSocket,otNetifIdentifier aNetifIdentifier)288 otError otPlatUdpBindToNetif(otUdpSocket *aUdpSocket, otNetifIdentifier aNetifIdentifier)
289 {
290     otError error = OT_ERROR_NONE;
291     int     fd    = FdFromHandle(aUdpSocket->mHandle);
292     int     one   = 1;
293     int     zero  = 0;
294 
295     switch (aNetifIdentifier)
296     {
297     case OT_NETIF_UNSPECIFIED:
298     {
299 #ifdef __linux__
300         VerifyOrExit(setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, nullptr, 0) == 0, error = OT_ERROR_FAILED);
301 #else  // __NetBSD__ || __FreeBSD__ || __APPLE__
302         unsigned int netifIndex = 0;
303         VerifyOrExit(setsockopt(fd, IPPROTO_IPV6, IPV6_BOUND_IF, &netifIndex, sizeof(netifIndex)) == 0,
304                                error = OT_ERROR_FAILED);
305 #endif // __linux__
306         break;
307     }
308     case OT_NETIF_THREAD:
309     {
310 #ifdef __linux__
311         VerifyOrExit(setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, &gNetifName, strlen(gNetifName)) == 0,
312                      error = OT_ERROR_FAILED);
313 #else  // __NetBSD__ || __FreeBSD__ || __APPLE__
314         VerifyOrExit(setsockopt(fd, IPPROTO_IPV6, IPV6_BOUND_IF, &gNetifIndex, sizeof(gNetifIndex)) == 0,
315                                error = OT_ERROR_FAILED);
316 #endif // __linux__
317         break;
318     }
319     case OT_NETIF_BACKBONE:
320     {
321 #if OPENTHREAD_CONFIG_BACKBONE_ROUTER_ENABLE
322         if (otSysGetInfraNetifName() == nullptr || otSysGetInfraNetifName()[0] == '\0')
323         {
324             ot::Posix::Udp::LogWarn("No backbone interface given, %s fails.", __func__);
325             ExitNow(error = OT_ERROR_INVALID_ARGS);
326         }
327 #ifdef __linux__
328         VerifyOrExit(setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, otSysGetInfraNetifName(),
329                                 strlen(otSysGetInfraNetifName())) == 0,
330                      error = OT_ERROR_FAILED);
331 #else  // __NetBSD__ || __FreeBSD__ || __APPLE__
332         uint32_t backboneNetifIndex = otSysGetInfraNetifIndex();
333         VerifyOrExit(setsockopt(fd, IPPROTO_IPV6, IPV6_BOUND_IF, &backboneNetifIndex, sizeof(backboneNetifIndex)) == 0,
334                      error = OT_ERROR_FAILED);
335 #endif // __linux__
336 #else
337         ExitNow(error = OT_ERROR_NOT_IMPLEMENTED);
338 #endif
339         VerifyOrExit(setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (char *)&one, sizeof(one)) == 0,
340                      error = OT_ERROR_FAILED);
341 
342         break;
343     }
344     }
345 
346     VerifyOrExit(setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &zero, sizeof(zero)) == 0, error = OT_ERROR_FAILED);
347 
348 exit:
349     return error;
350 }
351 
otPlatUdpConnect(otUdpSocket * aUdpSocket)352 otError otPlatUdpConnect(otUdpSocket *aUdpSocket)
353 {
354     otError             error = OT_ERROR_NONE;
355     struct sockaddr_in6 sin6;
356     int                 fd;
357     bool isDisconnect = IsIp6AddressUnspecified(aUdpSocket->mPeerName.mAddress) && (aUdpSocket->mPeerName.mPort == 0);
358 
359     VerifyOrExit(aUdpSocket->mHandle != nullptr, error = OT_ERROR_INVALID_ARGS);
360 
361     fd = FdFromHandle(aUdpSocket->mHandle);
362 
363     memset(&sin6, 0, sizeof(struct sockaddr_in6));
364     sin6.sin6_port = htons(aUdpSocket->mPeerName.mPort);
365 
366     if (!isDisconnect)
367     {
368         sin6.sin6_family = AF_INET6;
369         CopyIp6AddressTo(aUdpSocket->mPeerName.mAddress, &sin6.sin6_addr);
370     }
371     else
372     {
373 #ifdef __APPLE__
374         sin6.sin6_family = AF_UNSPEC;
375 #else
376         char      netifName[IFNAMSIZ];
377         socklen_t len = sizeof(netifName);
378 
379         if (getsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, &netifName, &len) != 0)
380         {
381                       ot::Posix::Udp::LogWarn("Failed to read socket bound device: %s", strerror(errno));
382                       len = 0;
383         }
384 
385         // There is a bug in linux that connecting to AF_UNSPEC does not disconnect.
386         // We create new socket to disconnect.
387         SuccessOrExit(error = otPlatUdpClose(aUdpSocket));
388         SuccessOrExit(error = otPlatUdpSocket(aUdpSocket));
389         SuccessOrExit(error = otPlatUdpBind(aUdpSocket));
390 
391         if (len > 0 && netifName[0] != '\0')
392         {
393                       fd = FdFromHandle(aUdpSocket->mHandle);
394                       VerifyOrExit(setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, &netifName, len) == 0, {
395                           ot::Posix::Udp::LogWarn("Failed to bind to device: %s", strerror(errno));
396                           error = OT_ERROR_FAILED;
397                       });
398         }
399 
400         ExitNow();
401 #endif
402     }
403 
404     if (connect(fd, reinterpret_cast<struct sockaddr *>(&sin6), sizeof(sin6)) != 0)
405     {
406 #ifdef __APPLE__
407         VerifyOrExit(errno == EAFNOSUPPORT && isDisconnect);
408 #endif
409         ot::Posix::Udp::LogWarn("Failed to connect to [%s]:%u: %s",
410                                 Ip6AddressString(&aUdpSocket->mPeerName.mAddress).AsCString(),
411                                 aUdpSocket->mPeerName.mPort, strerror(errno));
412         error = OT_ERROR_FAILED;
413     }
414 
415 exit:
416     return error;
417 }
418 
otPlatUdpSend(otUdpSocket * aUdpSocket,otMessage * aMessage,const otMessageInfo * aMessageInfo)419 otError otPlatUdpSend(otUdpSocket *aUdpSocket, otMessage *aMessage, const otMessageInfo *aMessageInfo)
420 {
421     otError  error = OT_ERROR_NONE;
422     int      fd;
423     uint16_t len;
424     uint8_t  payload[kMaxUdpSize];
425 
426     VerifyOrExit(aUdpSocket->mHandle != nullptr, error = OT_ERROR_INVALID_ARGS);
427     fd = FdFromHandle(aUdpSocket->mHandle);
428 
429     len = otMessageGetLength(aMessage);
430     VerifyOrExit(len == otMessageRead(aMessage, 0, payload, len), error = OT_ERROR_INVALID_ARGS);
431 
432     if (aMessageInfo->mMulticastLoop)
433     {
434         int value = 1;
435 
436         VerifyOrDie(setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &value, sizeof(value)) == 0, OT_EXIT_ERROR_ERRNO);
437     }
438 
439     error = transmitPacket(fd, payload, len, *aMessageInfo);
440 
441     if (aMessageInfo->mMulticastLoop)
442     {
443         int value = 0;
444 
445         VerifyOrDie(setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &value, sizeof(value)) == 0, OT_EXIT_ERROR_ERRNO);
446     }
447 
448 exit:
449     if (error == OT_ERROR_NONE)
450     {
451         otMessageFree(aMessage);
452     }
453 
454     return error;
455 }
456 
otPlatUdpJoinMulticastGroup(otUdpSocket * aUdpSocket,otNetifIdentifier aNetifIdentifier,const otIp6Address * aAddress)457 otError otPlatUdpJoinMulticastGroup(otUdpSocket        *aUdpSocket,
458                                     otNetifIdentifier   aNetifIdentifier,
459                                     const otIp6Address *aAddress)
460 {
461     otError          error = OT_ERROR_NONE;
462     struct ipv6_mreq mreq;
463     int              fd;
464 
465     VerifyOrExit(aUdpSocket->mHandle != nullptr, error = OT_ERROR_INVALID_ARGS);
466     fd = FdFromHandle(aUdpSocket->mHandle);
467 
468     CopyIp6AddressTo(*aAddress, &mreq.ipv6mr_multiaddr);
469 
470     switch (aNetifIdentifier)
471     {
472     case OT_NETIF_UNSPECIFIED:
473         break;
474     case OT_NETIF_THREAD:
475         mreq.ipv6mr_interface = gNetifIndex;
476         break;
477     case OT_NETIF_BACKBONE:
478 #if OPENTHREAD_CONFIG_BACKBONE_ROUTER_ENABLE
479         mreq.ipv6mr_interface = otSysGetInfraNetifIndex();
480 #else
481         ExitNow(error = OT_ERROR_NOT_IMPLEMENTED);
482 #endif
483         break;
484     }
485 
486     VerifyOrExit(setsockopt(fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq, sizeof(mreq)) == 0 || errno == EADDRINUSE,
487                  error = OT_ERROR_FAILED);
488 
489 exit:
490     if (error != OT_ERROR_NONE)
491     {
492         ot::Posix::Udp::LogCrit("IPV6_JOIN_GROUP failed: %s", strerror(errno));
493     }
494 
495     return error;
496 }
497 
otPlatUdpLeaveMulticastGroup(otUdpSocket * aUdpSocket,otNetifIdentifier aNetifIdentifier,const otIp6Address * aAddress)498 otError otPlatUdpLeaveMulticastGroup(otUdpSocket        *aUdpSocket,
499                                      otNetifIdentifier   aNetifIdentifier,
500                                      const otIp6Address *aAddress)
501 {
502     otError          error = OT_ERROR_NONE;
503     struct ipv6_mreq mreq;
504     int              fd;
505 
506     VerifyOrExit(aUdpSocket->mHandle != nullptr, error = OT_ERROR_INVALID_ARGS);
507     fd = FdFromHandle(aUdpSocket->mHandle);
508 
509     CopyIp6AddressTo(*aAddress, &mreq.ipv6mr_multiaddr);
510 
511     switch (aNetifIdentifier)
512     {
513     case OT_NETIF_UNSPECIFIED:
514         break;
515     case OT_NETIF_THREAD:
516         mreq.ipv6mr_interface = gNetifIndex;
517         break;
518     case OT_NETIF_BACKBONE:
519 #if OPENTHREAD_CONFIG_BACKBONE_ROUTER_ENABLE
520         mreq.ipv6mr_interface = otSysGetInfraNetifIndex();
521 #else
522         ExitNow(error = OT_ERROR_NOT_IMPLEMENTED);
523 #endif
524         break;
525     }
526 
527     VerifyOrExit(setsockopt(fd, IPPROTO_IPV6, IPV6_LEAVE_GROUP, &mreq, sizeof(mreq)) == 0 || errno == EADDRINUSE,
528                  error = OT_ERROR_FAILED);
529 
530 exit:
531     if (error != OT_ERROR_NONE)
532     {
533         ot::Posix::Udp::LogCrit("IPV6_LEAVE_GROUP failed: %s", strerror(errno));
534     }
535 
536     return error;
537 }
538 
539 namespace ot {
540 namespace Posix {
541 
542 const char Udp::kLogModuleName[] = "Udp";
543 
Update(otSysMainloopContext & aContext)544 void Udp::Update(otSysMainloopContext &aContext)
545 {
546     VerifyOrExit(gNetifIndex != 0);
547 
548     for (otUdpSocket *socket = otUdpGetSockets(gInstance); socket != nullptr; socket = socket->mNext)
549     {
550         int fd;
551 
552         if (socket->mHandle == nullptr)
553         {
554             continue;
555         }
556 
557         fd = FdFromHandle(socket->mHandle);
558         FD_SET(fd, &aContext.mReadFdSet);
559 
560         if (aContext.mMaxFd < fd)
561         {
562             aContext.mMaxFd = fd;
563         }
564     }
565 
566 exit:
567     return;
568 }
569 
Init(const char * aIfName)570 void Udp::Init(const char *aIfName)
571 {
572     if (aIfName == nullptr)
573     {
574         DieNow(OT_EXIT_INVALID_ARGUMENTS);
575     }
576 
577     if (aIfName != gNetifName)
578     {
579         VerifyOrDie(strlen(aIfName) < sizeof(gNetifName) - 1, OT_EXIT_INVALID_ARGUMENTS);
580         assert(gNetifIndex == 0);
581         strcpy(gNetifName, aIfName);
582         gNetifIndex = if_nametoindex(gNetifName);
583         VerifyOrDie(gNetifIndex != 0, OT_EXIT_ERROR_ERRNO);
584     }
585 
586     assert(gNetifIndex != 0);
587 }
588 
SetUp(void)589 void Udp::SetUp(void) { Mainloop::Manager::Get().Add(*this); }
590 
TearDown(void)591 void Udp::TearDown(void) { Mainloop::Manager::Get().Remove(*this); }
592 
Deinit(void)593 void Udp::Deinit(void)
594 {
595     // TODO All platform sockets should be closed
596 }
597 
Get(void)598 Udp &Udp::Get(void)
599 {
600     static Udp sInstance;
601 
602     return sInstance;
603 }
604 
Process(const otSysMainloopContext & aContext)605 void Udp::Process(const otSysMainloopContext &aContext)
606 {
607     otMessageSettings msgSettings = {false, OT_MESSAGE_PRIORITY_NORMAL};
608 
609     for (otUdpSocket *socket = otUdpGetSockets(gInstance); socket != nullptr; socket = socket->mNext)
610     {
611         int fd = FdFromHandle(socket->mHandle);
612 
613         if (fd > 0 && FD_ISSET(fd, &aContext.mReadFdSet))
614         {
615             otMessageInfo messageInfo;
616             otMessage    *message = nullptr;
617             uint8_t       payload[kMaxUdpSize];
618             uint16_t      length = sizeof(payload);
619 
620             memset(&messageInfo, 0, sizeof(messageInfo));
621             messageInfo.mSockPort = socket->mSockName.mPort;
622 
623             if (OT_ERROR_NONE != receivePacket(fd, payload, length, messageInfo))
624             {
625                 continue;
626             }
627 
628             message = otUdpNewMessage(gInstance, &msgSettings);
629 
630             if (message == nullptr)
631             {
632                 continue;
633             }
634 
635             if (otMessageAppend(message, payload, length) != OT_ERROR_NONE)
636             {
637                 otMessageFree(message);
638                 continue;
639             }
640 
641             socket->mHandler(socket->mContext, message, &messageInfo);
642             otMessageFree(message);
643             // only process one socket a time
644             break;
645         }
646     }
647 
648     return;
649 }
650 
651 } // namespace Posix
652 } // namespace ot
653 #endif // #if OPENTHREAD_CONFIG_PLATFORM_UDP_ENABLE
654