1 /* ****************************************************************
3 * Copyright 2014 Samsung Electronics All Rights Reserved.
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
19 ******************************************************************/
21 #ifndef __APPLE_USE_RFC_3542
22 #define __APPLE_USE_RFC_3542 // for PKTINFO
25 #define _GNU_SOURCE // for in6_pktinfo
28 #include <sys/types.h>
29 #if !defined(__msys_nt__)
30 #include <sys/socket.h>
33 #if defined(__msys_nt__)
42 #include <sys/types.h>
44 #if !defined(__msys_nt__)
45 #include <sys/select.h>
46 #include <arpa/inet.h>
47 #include <netinet/in.h>
52 #include <linux/netlink.h>
53 #include <linux/rtnetlink.h>
57 #include "caipinterface.h"
58 #include "caadapterutils.h"
60 #include "caadapternetdtls.h"
63 #include "oic_malloc.h"
64 #include "oic_string.h"
72 * Logging tag for module name
74 #define TAG "OIC_CA_IP_SERVER"
76 #define SELECT_TIMEOUT 1 // select() seconds (and termination latency)
78 #define IPv4_MULTICAST "224.0.1.187"
79 static struct in_addr IPv4MulticastAddress = { 0 };
81 #define IPv6_DOMAINS 16
82 #define IPv6_MULTICAST_INT "ff01::fd"
83 static struct in6_addr IPv6MulticastAddressInt;
84 #define IPv6_MULTICAST_LNK "ff02::fd"
85 static struct in6_addr IPv6MulticastAddressLnk;
86 #define IPv6_MULTICAST_RLM "ff03::fd"
87 static struct in6_addr IPv6MulticastAddressRlm;
88 #define IPv6_MULTICAST_ADM "ff04::fd"
89 static struct in6_addr IPv6MulticastAddressAdm;
90 #define IPv6_MULTICAST_SIT "ff05::fd"
91 static struct in6_addr IPv6MulticastAddressSit;
92 #define IPv6_MULTICAST_ORG "ff08::fd"
93 static struct in6_addr IPv6MulticastAddressOrg;
94 #define IPv6_MULTICAST_GLB "ff0e::fd"
95 static struct in6_addr IPv6MulticastAddressGlb;
97 static char *ipv6mcnames[IPv6_DOMAINS] = {
117 #define IFF_UP_RUNNING_FLAGS (IFF_UP)
119 char* caips_get_error(){
120 static char buffer[32];
121 snprintf(buffer, 32, "%i", WSAGetLastError());
124 #define CAIPS_GET_ERROR \
127 #define IFF_UP_RUNNING_FLAGS (IFF_UP|IFF_RUNNING)
129 #define CAIPS_GET_ERROR \
132 static CAIPExceptionCallback g_exceptionCallback;
134 static CAIPPacketReceivedCallback g_packetReceivedCallback;
136 static void CAHandleNetlink();
137 static void CAFindReadyMessage();
138 static void CASelectReturned(fd_set *readFds, int ret);
139 static void CAProcessNewInterface(CAInterface_t *ifchanged);
140 static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags);
142 #define SET(TYPE, FDS) \
143 if (caglobals.ip.TYPE.fd != -1) \
145 FD_SET(caglobals.ip.TYPE.fd, FDS); \
148 #define ISSET(TYPE, FDS, FLAGS) \
149 if (caglobals.ip.TYPE.fd != -1 && FD_ISSET(caglobals.ip.TYPE.fd, FDS)) \
151 fd = caglobals.ip.TYPE.fd; \
155 #define CLOSE_SOCKET(TYPE) \
156 if (caglobals.ip.TYPE.fd != -1) \
158 close(caglobals.ip.TYPE.fd); \
159 caglobals.ip.TYPE.fd = -1; \
162 void CADeInitializeIPGlobals()
173 if (caglobals.ip.netlinkFd != -1)
175 close(caglobals.ip.netlinkFd);
176 caglobals.ip.netlinkFd = -1;
180 static void CAReceiveHandler(void *data)
184 while (!caglobals.ip.terminate)
186 CAFindReadyMessage();
190 static void CAFindReadyMessage()
193 struct timeval timeout;
195 timeout.tv_sec = caglobals.ip.selectTimeout;
197 struct timeval *tv = caglobals.ip.selectTimeout == -1 ? NULL : &timeout;
210 if (caglobals.ip.shutdownFds[0] != -1)
212 FD_SET(caglobals.ip.shutdownFds[0], &readFds);
214 if (caglobals.ip.netlinkFd != -1)
216 FD_SET(caglobals.ip.netlinkFd, &readFds);
219 int ret = select(caglobals.ip.maxfd + 1, &readFds, NULL, NULL, tv);
221 if (caglobals.ip.terminate)
223 OIC_LOG_V(DEBUG, TAG, "Packet receiver Stop request received.");
231 OIC_LOG_V(FATAL, TAG, "select error %s", CAIPS_GET_ERROR);
236 CASelectReturned(&readFds, ret);
239 static void CASelectReturned(fd_set *readFds, int ret)
243 CATransportFlags_t flags = CA_DEFAULT_FLAGS;
245 while (!caglobals.ip.terminate)
247 ISSET(u6, readFds, CA_IPV6)
248 else ISSET(u6s, readFds, CA_IPV6 | CA_SECURE)
249 else ISSET(u4, readFds, CA_IPV4)
250 else ISSET(u4s, readFds, CA_IPV4 | CA_SECURE)
251 else ISSET(m6, readFds, CA_MULTICAST | CA_IPV6)
252 else ISSET(m6s, readFds, CA_MULTICAST | CA_IPV6 | CA_SECURE)
253 else ISSET(m4, readFds, CA_MULTICAST | CA_IPV4)
254 else ISSET(m4s, readFds, CA_MULTICAST | CA_IPV4 | CA_SECURE)
256 else if (FD_ISSET(caglobals.ip.netlinkFd, readFds))
258 CAInterface_t *ifchanged = CAFindInterfaceChange();
261 CAProcessNewInterface(ifchanged);
266 else if (FD_ISSET(caglobals.ip.shutdownFds[0], readFds))
269 ssize_t len = read(caglobals.ip.shutdownFds[0], buf, sizeof (buf));
286 (void)CAReceiveMessage(fd, flags);
291 static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags)
293 char recvBuffer[COAP_MAX_PDU_SIZE];
296 int level, type, namelen;
297 struct sockaddr_storage srcAddr;
298 unsigned char *pktinfo = NULL;
299 #if !defined(WSA_CMSG_DATA)
300 struct cmsghdr *cmp = NULL;
301 struct iovec iov = { .iov_base = recvBuffer, .iov_len = sizeof (recvBuffer) };
305 unsigned char data[CMSG_SPACE(sizeof (struct in6_pktinfo))];
310 namelen = sizeof (struct sockaddr_in6);
311 level = IPPROTO_IPV6;
313 len = sizeof (struct in6_pktinfo);
317 namelen = sizeof (struct sockaddr_in);
320 len = sizeof (struct in6_pktinfo);
323 struct msghdr msg = { .msg_name = &srcAddr,
324 .msg_namelen = namelen,
327 .msg_control = &cmsg,
328 .msg_controllen = CMSG_SPACE(len) };
330 ssize_t recvLen = recvmsg(fd, &msg, flags);
333 OIC_LOG_V(ERROR, TAG, "Recvfrom failed %s", strerror(errno));
334 return CA_STATUS_FAILED;
337 if (flags & CA_MULTICAST)
339 for (cmp = CMSG_FIRSTHDR(&msg); cmp != NULL; cmp = CMSG_NXTHDR(&msg, cmp))
341 if (cmp->cmsg_level == level && cmp->cmsg_type == type)
343 pktinfo = CMSG_DATA(cmp);
347 #else // if defined(WSA_CMSG_DATA)
351 uint8_t data[WSA_CMSG_SPACE(sizeof (IN6_PKTINFO))];
353 memset(&cmsg, 0, sizeof(cmsg));
357 namelen = sizeof (struct sockaddr_in6);
358 level = IPPROTO_IPV6;
363 namelen = sizeof (struct sockaddr_in);
368 WSABUF iov = {.len = sizeof (recvBuffer), .buf = recvBuffer};
369 WSAMSG msg = {.name = &srcAddr,
373 .Control = {.buf = cmsg.data, .len = sizeof (cmsg)}
376 uint32_t recvLen = 0;
377 uint32_t ret = caglobals.ip.wsaRecvMsg(fd, &msg, &recvLen, 0,0);
378 OIC_LOG_V(DEBUG, TAG, "WSARecvMsg recvd %u bytes", recvLen);
379 if (SOCKET_ERROR == ret)
381 OIC_LOG_V(ERROR, TAG, "WSARecvMsg failed %i", WSAGetLastError());
384 if (flags & CA_MULTICAST)
386 for (WSACMSGHDR *cmp = WSA_CMSG_FIRSTHDR(&msg); cmp != NULL;
387 cmp = WSA_CMSG_NXTHDR(&msg, cmp))
389 if (cmp->cmsg_level == level && cmp->cmsg_type == type)
391 pktinfo = WSA_CMSG_DATA(cmp);
395 #endif // !defined(WSA_CMSG_DATA)
396 CASecureEndpoint_t sep = {.endpoint = {.adapter = CA_ADAPTER_IP, .flags = flags}};
400 /** @todo figure out correct usage for ifindex, and sin6_scope_id.*/
401 if ((flags & CA_MULTICAST) && pktinfo)
403 struct in6_addr *addr = &(((struct in6_pktinfo *)pktinfo)->ipi6_addr);
404 unsigned char topbits = ((unsigned char *)addr)[0];
407 sep.endpoint.flags &= ~CA_MULTICAST;
413 if ((flags & CA_MULTICAST) && pktinfo)
415 struct in_addr *addr = &((struct in_pktinfo *)pktinfo)->ipi_addr;
416 uint32_t host = ntohl(addr->s_addr);
417 unsigned char topbits = ((unsigned char *)&host)[3];
418 if (topbits < 224 || topbits > 239)
420 sep.endpoint.flags &= ~CA_MULTICAST;
425 CAConvertAddrToName(&srcAddr, namelen, sep.endpoint.addr, &sep.endpoint.port);
427 if (flags & CA_SECURE)
430 int ret = CAAdapterNetDtlsDecrypt(&sep, (uint8_t *)recvBuffer, recvLen);
431 OIC_LOG_V(DEBUG, TAG, "CAAdapterNetDtlsDecrypt returns [%d]", ret);
433 OIC_LOG(ERROR, TAG, "Encrypted message but no DTLS");
438 if (g_packetReceivedCallback)
440 g_packetReceivedCallback(&sep, recvBuffer, recvLen);
450 OIC_LOG(DEBUG, TAG, "IN");
451 OIC_LOG(DEBUG, TAG, "OUT");
454 static int CACreateSocket(int family, uint16_t *port)
456 int socktype = SOCK_DGRAM;
458 socktype |= SOCK_CLOEXEC;
460 int fd = socket(family, socktype, IPPROTO_UDP);
463 OIC_LOG_V(ERROR, TAG, "create socket failed: %s", CAIPS_GET_ERROR);
467 #if !defined(SOCK_CLOEXEC) && defined(FD_CLOEXEC)
468 int fl = fcntl(fd, F_GETFD);
469 if (-1 == fl || -1 == fcntl(fd, F_SETFD, fl|FD_CLOEXEC))
471 OIC_LOG_V(ERROR, TAG, "set FD_CLOEXEC failed: %s", strerror(errno));
476 struct sockaddr_storage sa = { .ss_family = family };
479 if (family == AF_INET6)
483 if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
485 OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", CAIPS_GET_ERROR);
488 if (*port) // only do this for multicast ports
490 #if defined(IPV6_RECVPKTINFO)
491 if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof (on)))
493 if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_PKTINFO, &on, sizeof (on)))
496 OIC_LOG_V(ERROR, TAG, "IPV6_RECVPKTINFO failed: %s",CAIPS_GET_ERROR);
500 ((struct sockaddr_in6 *)&sa)->sin6_port = htons(*port);
501 socklen = sizeof (struct sockaddr_in6);
505 if (*port) // only do this for multicast ports
508 if (-1 == setsockopt(fd, IPPROTO_IP, IP_PKTINFO, &on, sizeof (on)))
510 OIC_LOG_V(ERROR, TAG, "IP_PKTINFO failed: %s", CAIPS_GET_ERROR);
514 ((struct sockaddr_in *)&sa)->sin_port = htons(*port);
515 socklen = sizeof (struct sockaddr_in);
518 if (*port) // use the given port
521 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof (on)))
523 OIC_LOG_V(ERROR, TAG, "SO_REUSEADDR failed: %s", CAIPS_GET_ERROR);
529 if (-1 == bind(fd, (struct sockaddr *)&sa, socklen))
531 OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", CAIPS_GET_ERROR);
536 if (!*port) // return the assigned port
538 if (-1 == getsockname(fd, (struct sockaddr *)&sa, &socklen))
540 OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", CAIPS_GET_ERROR);
544 *port = ntohs(family == AF_INET6 ?
545 ((struct sockaddr_in6 *)&sa)->sin6_port :
546 ((struct sockaddr_in *)&sa)->sin_port);
552 #define CHECKFD(FD) \
553 if (FD > caglobals.ip.maxfd) \
554 caglobals.ip.maxfd = FD;
555 #define NEWSOCKET(FAMILY, NAME) \
556 caglobals.ip.NAME.fd = CACreateSocket(FAMILY, &caglobals.ip.NAME.port); \
557 CHECKFD(caglobals.ip.NAME.fd)
559 static void CAInitializeNetlink()
562 // create NETLINK fd for interface change notifications
563 struct sockaddr_nl sa = { AF_NETLINK, 0, 0, RTMGRP_LINK };
565 caglobals.ip.netlinkFd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC, NETLINK_ROUTE);
566 if (caglobals.ip.netlinkFd == -1)
568 OIC_LOG_V(ERROR, TAG, "netlink socket failed: %s", strerror(errno));
572 int r = bind(caglobals.ip.netlinkFd, (struct sockaddr *)&sa, sizeof (sa));
575 OIC_LOG_V(ERROR, TAG, "netlink bind failed: %s", strerror(errno));
576 close(caglobals.ip.netlinkFd);
577 caglobals.ip.netlinkFd = -1;
581 CHECKFD(caglobals.ip.netlinkFd);
587 static void CAInitializePipe()
590 caglobals.ip.selectTimeout = -1;
592 int ret = pipe2(caglobals.ip.shutdownFds, O_CLOEXEC);
594 int ret = pipe(caglobals.ip.shutdownFds);
597 ret = fcntl(caglobals.ip.shutdownFds[0], F_GETFD);
600 ret = fcntl(caglobals.ip.shutdownFds[0], F_SETFD, ret|FD_CLOEXEC);
604 ret = fcntl(caglobals.ip.shutdownFds[1], F_GETFD);
608 ret = fcntl(caglobals.ip.shutdownFds[1], F_SETFD, ret|FD_CLOEXEC);
612 close(caglobals.ip.shutdownFds[1]);
613 close(caglobals.ip.shutdownFds[0]);
614 caglobals.ip.shutdownFds[0] = -1;
615 caglobals.ip.shutdownFds[1] = -1;
621 OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
622 caglobals.ip.selectTimeout = SELECT_TIMEOUT; //poll needed for shutdown
625 /** @todo Refactor to support Windows-specific inter-thread communication code. */
629 CAResult_t CAIPStartServer(const ca_thread_pool_t threadPool)
631 CAResult_t res = CA_STATUS_OK;
633 if (caglobals.ip.started)
638 WORD wVersionRequested = MAKEWORD(2, 2);
639 WSADATA wsaData ={.wVersion = 0};
640 int err = WSAStartup(wVersionRequested, &wsaData);
643 OIC_LOG_V(ERROR, TAG, "WSAStartup failed: %i", err);
644 return CA_STATUS_FAILED;
646 OIC_LOG(DEBUG, TAG, "WSAStartup Succeeded");
648 if (!IPv4MulticastAddress.s_addr)
650 (void)inet_pton(AF_INET, IPv4_MULTICAST, &IPv4MulticastAddress);
651 (void)inet_pton(AF_INET6, IPv6_MULTICAST_INT, &IPv6MulticastAddressInt);
652 (void)inet_pton(AF_INET6, IPv6_MULTICAST_LNK, &IPv6MulticastAddressLnk);
653 (void)inet_pton(AF_INET6, IPv6_MULTICAST_RLM, &IPv6MulticastAddressRlm);
654 (void)inet_pton(AF_INET6, IPv6_MULTICAST_ADM, &IPv6MulticastAddressAdm);
655 (void)inet_pton(AF_INET6, IPv6_MULTICAST_SIT, &IPv6MulticastAddressSit);
656 (void)inet_pton(AF_INET6, IPv6_MULTICAST_ORG, &IPv6MulticastAddressOrg);
657 (void)inet_pton(AF_INET6, IPv6_MULTICAST_GLB, &IPv6MulticastAddressGlb);
660 if (!caglobals.ip.ipv6enabled && !caglobals.ip.ipv4enabled)
662 caglobals.ip.ipv4enabled = true; // only needed to run CA tests
665 if (caglobals.ip.ipv6enabled)
667 NEWSOCKET(AF_INET6, u6)
668 NEWSOCKET(AF_INET6, u6s)
669 NEWSOCKET(AF_INET6, m6)
670 NEWSOCKET(AF_INET6, m6s)
671 OIC_LOG_V(INFO, TAG, "IPv6 unicast port: %u", caglobals.ip.u6.port);
673 if (caglobals.ip.ipv4enabled)
675 NEWSOCKET(AF_INET, u4)
676 NEWSOCKET(AF_INET, u4s)
677 NEWSOCKET(AF_INET, m4)
678 NEWSOCKET(AF_INET, m4s)
679 OIC_LOG_V(INFO, TAG, "IPv4 unicast port: %u", caglobals.ip.u4.port);
682 OIC_LOG_V(DEBUG, TAG,
683 "socket summary: u6=%d, u6s=%d, u4=%d, u4s=%d, m6=%d, m6s=%d, m4=%d, m4s=%d",
684 caglobals.ip.u6.fd, caglobals.ip.u6s.fd, caglobals.ip.u4.fd, caglobals.ip.u4s.fd,
685 caglobals.ip.m6.fd, caglobals.ip.m6s.fd, caglobals.ip.m4.fd, caglobals.ip.m4s.fd);
687 OIC_LOG_V(DEBUG, TAG,
688 "port summary: u6 port=%d, u6s port=%d, u4 port=%d, u4s port=%d, m6 port=%d,"
689 "m6s port=%d, m4 port=%d, m4s port=%d",
690 caglobals.ip.u6.port, caglobals.ip.u6s.port, caglobals.ip.u4.port,
691 caglobals.ip.u4s.port, caglobals.ip.m6.port, caglobals.ip.m6s.port,
692 caglobals.ip.m4.port, caglobals.ip.m4s.port);
694 caglobals.ip.wsaRecvMsg = NULL;
695 GUID GuidWSARecvMsg = WSAID_WSARECVMSG;
697 err = WSAIoctl(caglobals.ip.u4.fd, SIO_GET_EXTENSION_FUNCTION_POINTER, &GuidWSARecvMsg, sizeof(GuidWSARecvMsg), &(caglobals.ip.wsaRecvMsg), sizeof(caglobals.ip.wsaRecvMsg), &copied, 0, 0);
700 OIC_LOG_V(ERROR, TAG, "WSAIoctl failed %i", WSAGetLastError());
701 return CA_STATUS_FAILED;
704 // create pipe for fast shutdown
706 CHECKFD(caglobals.ip.shutdownFds[0]);
707 CHECKFD(caglobals.ip.shutdownFds[1]);
709 // create source of network interface change notifications
710 CAInitializeNetlink();
712 caglobals.ip.selectTimeout = CAGetPollingInterval(caglobals.ip.selectTimeout);
714 res = CAIPStartListenServer();
715 if (CA_STATUS_OK != res)
717 OIC_LOG_V(ERROR, TAG, "Failed to start listening server![%d]", res);
721 caglobals.ip.terminate = false;
722 res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
723 if (CA_STATUS_OK != res)
725 OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
728 OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
730 caglobals.ip.started = true;
734 void CAIPStopServer()
736 caglobals.ip.started = false;
737 caglobals.ip.terminate = true;
740 if (caglobals.ip.shutdownFds[1] != -1)
742 close(caglobals.ip.shutdownFds[1]);
743 // receive thread will stop immediately
747 // receive thread will stop in SELECT_TIMEOUT seconds.
750 /** @todo Refactor to support Windows-specific inter-thread communication code. */
754 void CAWakeUpForChange()
757 if (caglobals.ip.shutdownFds[1] != -1)
762 len = write(caglobals.ip.shutdownFds[1], "w", 1);
763 } while ((len == -1) && (errno == EINTR));
764 if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
766 OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
770 /** @todo Refactor to support Windows-specific inter-thread communication code. */
774 static void applyMulticastToInterface4(uint32_t ifindex)
776 if (!caglobals.ip.ipv4enabled)
781 #if defined(USE_IP_MREQN)
782 struct ip_mreqn mreq = { .imr_multiaddr = IPv4MulticastAddress,
783 .imr_address.s_addr = htonl(INADDR_ANY),
784 .imr_ifindex = ifindex };
786 struct ip_mreq mreq = { .imr_multiaddr = IPv4MulticastAddress,
787 .imr_interface.s_addr = htonl(ifindex) };
790 int ret = setsockopt(caglobals.ip.m4.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof (mreq));
793 #if !defined(WSAEINVAL)
794 if (EADDRINUSE != errno)
796 if (WSAEINVAL != WSAGetLastError()) // Joining multicast group more than once (IPv4 Flavor)
799 OIC_LOG_V(ERROR, TAG, " IPv4 IP_ADD_MEMBERSHIP failed: %s", CAIPS_GET_ERROR);
802 ret = setsockopt(caglobals.ip.m4s.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof (mreq));
805 #if !defined(WSAEINVAL)
806 if (EADDRINUSE != errno)
808 if (WSAEINVAL != WSAGetLastError()) // Joining multicast group more than once (IPv4 Flavor)
811 OIC_LOG_V(ERROR, TAG, "SECURE IPv4 IP_ADD_MEMBERSHIP failed: %s", CAIPS_GET_ERROR);
816 static void applyMulticast6(int fd, struct in6_addr *addr, uint32_t ifindex)
818 struct ipv6_mreq mreq = {.ipv6mr_multiaddr = *addr,
819 .ipv6mr_interface = ifindex };
820 int ret = setsockopt(fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq, sizeof (mreq));
824 if (EADDRINUSE != errno)
826 if (WSAEINVAL != WSAGetLastError()) // Joining multicast group more than once (IPv6 Flavor)
829 OIC_LOG_V(ERROR, TAG, "IPv6 IPV6_JOIN_GROUP failed: %s", CAIPS_GET_ERROR);
834 static void applyMulticastToInterface6(uint32_t ifindex)
836 if (!caglobals.ip.ipv6enabled)
840 //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressInt, ifindex);
841 applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressLnk, ifindex);
842 //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressRlm, ifindex);
843 //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressAdm, ifindex);
844 //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressSit, ifindex);
845 //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressOrg, ifindex);
846 //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressGlb, ifindex);
848 //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressInt, ifindex);
849 applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressLnk, ifindex);
850 //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressRlm, ifindex);
851 //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressAdm, ifindex);
852 //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressSit, ifindex);
853 //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressOrg, ifindex);
854 //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressGlb, ifindex);
857 CAResult_t CAIPStartListenServer()
859 u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
862 OIC_LOG_V(ERROR, TAG, "CAIPGetInterfaceInformation() failed: %s", strerror(errno));
863 return CA_STATUS_FAILED;
866 uint32_t len = u_arraylist_length(iflist);
867 OIC_LOG_V(DEBUG, TAG, "IP network interfaces found: %d", len);
869 for (uint32_t i = 0; i < len; i++)
871 CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
877 if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
881 if (ifitem->family == AF_INET)
883 OIC_LOG_V(DEBUG, TAG, "Adding IPv4 interface %i to multicast group", ifitem->index);
884 applyMulticastToInterface4(ifitem->index);
886 if (ifitem->family == AF_INET6)
888 OIC_LOG_V(DEBUG, TAG, "Adding IPv6 interface %i to multicast group", ifitem->index);
889 applyMulticastToInterface6(ifitem->index);
893 u_arraylist_destroy(iflist);
897 CAResult_t CAIPStopListenServer()
899 u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
902 OIC_LOG_V(ERROR, TAG, "Get interface info failed: %s", strerror(errno));
903 return CA_STATUS_FAILED;
906 uint32_t len = u_arraylist_length(iflist);
907 OIC_LOG_V(DEBUG, TAG, "IP network interfaces found: %d", len);
909 for (uint32_t i = 0; i < len; i++)
911 CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
917 if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
921 if (ifitem->family == AF_INET)
923 close(caglobals.ip.m4.fd);
924 close(caglobals.ip.m4s.fd);
925 caglobals.ip.m4.fd = -1;
926 caglobals.ip.m4s.fd = -1;
927 OIC_LOG_V(DEBUG, TAG, "IPv4 network interface: %s cloed", ifitem->name);
929 if (ifitem->family == AF_INET6)
931 close(caglobals.ip.m6.fd);
932 close(caglobals.ip.m6s.fd);
933 caglobals.ip.m6.fd = -1;
934 caglobals.ip.m6s.fd = -1;
935 OIC_LOG_V(DEBUG, TAG, "IPv6 network interface: %s", ifitem->name);
938 u_arraylist_destroy(iflist);
942 static void CAProcessNewInterface(CAInterface_t *ifitem)
946 OIC_LOG(DEBUG, TAG, "ifitem is null");
950 if (ifitem->family == AF_INET6)
952 applyMulticastToInterface6(ifitem->index);
954 if (ifitem->family == AF_INET)
956 applyMulticastToInterface4(ifitem->index);
960 void CAIPSetPacketReceiveCallback(CAIPPacketReceivedCallback callback)
962 g_packetReceivedCallback = callback;
965 void CAIPSetExceptionCallback(CAIPExceptionCallback callback)
967 g_exceptionCallback = callback;
970 void CAIPSetConnectionStateChangeCallback(CAIPConnectionStateChangeCallback callback)
972 CAIPSetNetworkMonitorCallback(callback);
975 static void sendData(int fd, const CAEndpoint_t *endpoint,
976 const void *data, uint32_t dlen,
977 const char *cast, const char *fam)
979 OIC_LOG(DEBUG, TAG, "IN");
983 OIC_LOG(DEBUG, TAG, "endpoint is null");
987 char *secure = (endpoint->flags & CA_SECURE) ? "secure " : "";
989 (void)secure; // eliminates release warning
993 struct sockaddr_storage sock;
994 CAConvertNameToAddr(endpoint->addr, endpoint->port, &sock);
997 if (sock.ss_family == AF_INET6)
999 /** @todo figure out correct usage for ifindex, and sin6_scope_id */
1000 socklen = sizeof(struct sockaddr_in6);
1004 socklen = sizeof(struct sockaddr_in);
1006 #if !defined(_WIN32)
1007 ssize_t len = sendto(fd, data, dlen, 0, (struct sockaddr *)&sock, socklen);
1010 OIC_LOG_V(ERROR, TAG, "%s%s %s sendTo failed: %s", secure, cast, fam, strerror(errno));
1014 OIC_LOG_V(INFO, TAG, "%s%s %s sendTo is successful: %zd bytes", secure, cast, fam, len);
1021 len = sendto(fd, ((char*)data) + sent, dlen - sent, 0, (struct sockaddr *)&sock, socklen);
1022 if (SOCKET_ERROR == len)
1024 err = WSAGetLastError();
1025 if ((WSAEWOULDBLOCK != err) && (WSAENOBUFS != err))
1027 OIC_LOG_V(ERROR, TAG, "%s%s %s sendTo failed: %i", secure, cast, fam, err);
1035 OIC_LOG_V(DEBUG, TAG, "%s%s %s sendTo (Partial Send) is successful: "
1036 "currently sent: %ld bytes, "
1037 "total sent: %ld bytes, "
1038 "remaining: %ld bytes",
1039 secure, cast, fam, len, sent, dlen-sent);
1043 OIC_LOG_V(INFO, TAG, "%s%s %s sendTo is successful: %ld bytes",
1044 secure, cast, fam, len);
1047 } while ((SOCKET_ERROR == len) && ((WSAEWOULDBLOCK == err) || (WSAENOBUFS == err)) || (sent < dlen));
1051 static void sendMulticastData6(const u_arraylist_t *iflist,
1052 CAEndpoint_t *endpoint,
1053 const void *data, uint32_t datalen)
1057 OIC_LOG(DEBUG, TAG, "endpoint is null");
1061 int scope = endpoint->flags & CA_SCOPE_MASK;
1062 char *ipv6mcname = ipv6mcnames[scope];
1065 OIC_LOG_V(INFO, TAG, "IPv6 multicast scope invalid: %d", scope);
1068 OICStrcpy(endpoint->addr, sizeof(endpoint->addr), ipv6mcname);
1069 int fd = caglobals.ip.u6.fd;
1071 uint32_t len = u_arraylist_length(iflist);
1072 for (uint32_t i = 0; i < len; i++)
1074 CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1079 if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
1083 if (ifitem->family != AF_INET6)
1088 int index = ifitem->index;
1089 if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, &index, sizeof (index)))
1091 OIC_LOG_V(ERROR, TAG, "setsockopt6 failed: %s", CAIPS_GET_ERROR);
1094 sendData(fd, endpoint, data, datalen, "multicast", "ipv6");
1098 static void sendMulticastData4(const u_arraylist_t *iflist,
1099 CAEndpoint_t *endpoint,
1100 const void *data, uint32_t datalen)
1102 VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
1104 #if defined(USE_IP_MREQN)
1105 struct ip_mreqn mreq = { .imr_multiaddr = IPv4MulticastAddress,
1106 .imr_address.s_addr = htonl(INADDR_ANY),
1109 struct ip_mreq mreq = { .imr_multiaddr = IPv4MulticastAddress,
1110 .imr_interface = {0}};
1113 OICStrcpy(endpoint->addr, sizeof(endpoint->addr), IPv4_MULTICAST);
1114 int fd = caglobals.ip.u4.fd;
1116 uint32_t len = u_arraylist_length(iflist);
1117 for (uint32_t i = 0; i < len; i++)
1119 CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1124 if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
1128 if (ifitem->family != AF_INET)
1132 #if defined(USE_IP_MREQN)
1133 mreq.imr_ifindex = ifitem->index;
1135 mreq.imr_interface.s_addr = htonl(ifitem->index);
1137 if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, &mreq, sizeof (mreq)))
1139 OIC_LOG_V(ERROR, TAG, "send IP_MULTICAST_IF failed: %s (using defualt)",
1142 sendData(fd, endpoint, data, datalen, "multicast", "ipv4");
1146 void CAIPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
1149 VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
1150 VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
1152 bool isSecure = (endpoint->flags & CA_SECURE) != 0;
1156 endpoint->port = isSecure ? CA_SECURE_COAP : CA_COAP;
1158 u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
1161 OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
1165 if ((endpoint->flags & CA_IPV6) && caglobals.ip.ipv6enabled)
1167 sendMulticastData6(iflist, endpoint, data, datalen);
1169 if ((endpoint->flags & CA_IPV4) && caglobals.ip.ipv4enabled)
1171 sendMulticastData4(iflist, endpoint, data, datalen);
1174 u_arraylist_destroy(iflist);
1178 if (!endpoint->port) // unicast discovery
1180 endpoint->port = isSecure ? CA_SECURE_COAP : CA_COAP;
1184 if (caglobals.ip.ipv6enabled && (endpoint->flags & CA_IPV6))
1186 fd = isSecure ? caglobals.ip.u6s.fd : caglobals.ip.u6.fd;
1187 #ifndef __WITH_DTLS__
1188 fd = caglobals.ip.u6.fd;
1190 sendData(fd, endpoint, data, datalen, "unicast", "ipv6");
1192 if (caglobals.ip.ipv4enabled && (endpoint->flags & CA_IPV4))
1194 fd = isSecure ? caglobals.ip.u4s.fd : caglobals.ip.u4.fd;
1195 #ifndef __WITH_DTLS__
1196 fd = caglobals.ip.u4.fd;
1198 sendData(fd, endpoint, data, datalen, "unicast", "ipv4");
1203 CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1205 VERIFY_NON_NULL(info, TAG, "info is NULL");
1206 VERIFY_NON_NULL(size, TAG, "size is NULL");
1208 u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
1211 OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
1212 return CA_STATUS_FAILED;
1215 uint32_t len = u_arraylist_length(iflist);
1216 uint32_t length = len;
1218 #ifdef __WITH_DTLS__
1219 //If DTLS is supported, each interface can support secure port as well
1223 CAEndpoint_t *eps = (CAEndpoint_t *)OICCalloc(length, sizeof (CAEndpoint_t));
1226 OIC_LOG(ERROR, TAG, "Malloc Failed");
1227 u_arraylist_destroy(iflist);
1228 return CA_MEMORY_ALLOC_FAILED;
1231 for (uint32_t i = 0, j = 0; i < len; i++)
1233 CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1239 eps[j].adapter = CA_ADAPTER_IP;
1242 if (ifitem->family == AF_INET6)
1244 eps[j].flags = CA_IPV6;
1245 eps[j].port = caglobals.ip.u6.port;
1249 eps[j].flags = CA_IPV4;
1250 eps[j].port = caglobals.ip.u4.port;
1251 /** @todo eps[j].addr not populated with IPv4 address string.
1252 * it was using ifitem->ipv4addr to accomplish this.
1253 * Need to understand what ipv4addr means to whom*/
1256 #ifdef __WITH_DTLS__
1259 eps[j].adapter = CA_ADAPTER_IP;
1262 if (ifitem->family == AF_INET6)
1264 eps[j].flags = CA_IPV6 | CA_SECURE;
1265 eps[j].port = caglobals.ip.u6s.port;
1269 eps[j].flags = CA_IPV4 | CA_SECURE;
1270 eps[j].port = caglobals.ip.u4s.port;
1271 inet_ntop(AF_INET, &(ifitem->ipv4addr), eps[j].addr, MAX_ADDR_STR_SIZE_CA);
1280 u_arraylist_destroy(iflist);
1282 return CA_STATUS_OK;