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>
30 #include <sys/socket.h>
42 #if !defined(_MSC_VER)
44 #endif //!defined(_MSC_VER)
45 #include <sys/types.h>
48 #include <sys/select.h>
49 #include <arpa/inet.h>
50 #include <netinet/in.h>
55 #include <linux/netlink.h>
56 #include <linux/rtnetlink.h>
60 #include "caipinterface.h"
61 #include "caadapterutils.h"
63 #include "caadapternetdtls.h"
66 #include "oic_malloc.h"
67 #include "oic_string.h"
68 #include "platform_features.h"
76 * Logging tag for module name
78 #define TAG "OIC_CA_IP_SERVER"
80 #define SELECT_TIMEOUT 1 // select() seconds (and termination latency)
82 #define IPv4_MULTICAST "224.0.1.187"
83 static struct in_addr IPv4MulticastAddress = { 0 };
85 #define IPv6_DOMAINS 16
86 #define IPv6_MULTICAST_INT "ff01::fd"
87 static struct in6_addr IPv6MulticastAddressInt;
88 #define IPv6_MULTICAST_LNK "ff02::fd"
89 static struct in6_addr IPv6MulticastAddressLnk;
90 #define IPv6_MULTICAST_RLM "ff03::fd"
91 static struct in6_addr IPv6MulticastAddressRlm;
92 #define IPv6_MULTICAST_ADM "ff04::fd"
93 static struct in6_addr IPv6MulticastAddressAdm;
94 #define IPv6_MULTICAST_SIT "ff05::fd"
95 static struct in6_addr IPv6MulticastAddressSit;
96 #define IPv6_MULTICAST_ORG "ff08::fd"
97 static struct in6_addr IPv6MulticastAddressOrg;
98 #define IPv6_MULTICAST_GLB "ff0e::fd"
99 static struct in6_addr IPv6MulticastAddressGlb;
101 static char *ipv6mcnames[IPv6_DOMAINS] = {
121 #define IFF_UP_RUNNING_FLAGS (IFF_UP)
123 char* caips_get_error(){
124 static char buffer[32];
125 snprintf(buffer, 32, "%i", WSAGetLastError());
128 #define CAIPS_GET_ERROR \
131 #define IFF_UP_RUNNING_FLAGS (IFF_UP|IFF_RUNNING)
133 #define CAIPS_GET_ERROR \
136 static CAIPErrorHandleCallback g_ipErrorHandler = NULL;
138 static CAIPPacketReceivedCallback g_packetReceivedCallback = NULL;
140 static void CAHandleNetlink();
141 static void CAFindReadyMessage();
142 #if !defined(WSA_WAIT_EVENT_0)
143 static void CASelectReturned(fd_set *readFds, int ret);
145 static void CAEventReturned(HANDLE);
147 static void CAProcessNewInterface(CAInterface_t *ifchanged);
148 static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags);
150 static void CAReceiveHandler(void *data)
154 while (!caglobals.ip.terminate)
156 CAFindReadyMessage();
160 #if !defined(WSA_WAIT_EVENT_0)
162 #define CLOSE_SOCKET(TYPE) \
163 if (caglobals.ip.TYPE.fd != -1) \
165 close(caglobals.ip.TYPE.fd); \
166 caglobals.ip.TYPE.fd = -1; \
169 #define SET(TYPE, FDS) \
170 if (caglobals.ip.TYPE.fd != -1) \
172 FD_SET(caglobals.ip.TYPE.fd, FDS); \
175 #define ISSET(TYPE, FDS, FLAGS) \
176 if (caglobals.ip.TYPE.fd != -1 && FD_ISSET(caglobals.ip.TYPE.fd, FDS)) \
178 fd = caglobals.ip.TYPE.fd; \
183 static void CAFindReadyMessage()
186 struct timeval timeout;
188 timeout.tv_sec = caglobals.ip.selectTimeout;
190 struct timeval *tv = caglobals.ip.selectTimeout == -1 ? NULL : &timeout;
202 if (caglobals.ip.shutdownFds[0] != -1)
204 FD_SET(caglobals.ip.shutdownFds[0], &readFds);
206 if (caglobals.ip.netlinkFd != -1)
208 FD_SET(caglobals.ip.netlinkFd, &readFds);
211 int ret = select(caglobals.ip.maxfd + 1, &readFds, NULL, NULL, tv);
213 if (caglobals.ip.terminate)
215 OIC_LOG_V(DEBUG, TAG, "Packet receiver Stop request received.");
223 OIC_LOG_V(FATAL, TAG, "select error %s", CAIPS_GET_ERROR);
228 CASelectReturned(&readFds, ret);
231 static void CASelectReturned(fd_set *readFds, int ret)
235 CATransportFlags_t flags = CA_DEFAULT_FLAGS;
237 while (!caglobals.ip.terminate)
239 ISSET(u6, readFds, CA_IPV6)
240 else ISSET(u6s, readFds, CA_IPV6 | CA_SECURE)
241 else ISSET(u4, readFds, CA_IPV4)
242 else ISSET(u4s, readFds, CA_IPV4 | CA_SECURE)
243 else ISSET(m6, readFds, CA_MULTICAST | CA_IPV6)
244 else ISSET(m6s, readFds, CA_MULTICAST | CA_IPV6 | CA_SECURE)
245 else ISSET(m4, readFds, CA_MULTICAST | CA_IPV4)
246 else ISSET(m4s, readFds, CA_MULTICAST | CA_IPV4 | CA_SECURE)
247 else if ((caglobals.ip.netlinkFd != -1) && FD_ISSET(caglobals.ip.netlinkFd, readFds))
249 CAInterface_t *ifchanged = CAFindInterfaceChange();
252 CAProcessNewInterface(ifchanged);
257 else if (FD_ISSET(caglobals.ip.shutdownFds[0], readFds))
260 ssize_t len = read(caglobals.ip.shutdownFds[0], buf, sizeof (buf));
271 (void)CAReceiveMessage(fd, flags);
276 #else // if defined(WSA_WAIT_EVENT_0)
278 #define CLOSE_SOCKET(TYPE) \
279 if (caglobals.ip.TYPE.fd != -1) \
281 closesocket(caglobals.ip.TYPE.fd); \
282 caglobals.ip.TYPE.fd = -1; \
285 #define PUSH_HANDLE(HANDLE, ARRAY, INDEX) \
287 ARRAY[INDEX] = HANDLE; \
291 // Turn handle into WSAEvent and push to ARRAY
292 #define PUSH_SOCKET(SOCKET, ARRAY, INDEX) \
296 NewEvent = WSACreateEvent(); \
297 if (WSA_INVALID_EVENT != NewEvent) \
299 if (0 != WSAEventSelect(SOCKET, NewEvent, FD_READ)) \
301 OIC_LOG_V(ERROR, TAG, "WSAEventSelect failed 0x%08x ", WSAGetLastError()); \
302 if (!WSACloseEvent(NewEvent)) \
304 OIC_LOG_V(ERROR, TAG, "WSACloseEvent(NewEvent) failed 0x%08x", WSAGetLastError()); \
309 PUSH_HANDLE(NewEvent, ARRAY, INDEX); \
314 OIC_LOG_V(ERROR, TAG, "WSACreateEvent(NewEvent) failed 0x%08x", WSAGetLastError()); \
318 #define INSERT_FD(FD, ARRAY, INDEX) \
327 // Inserts the FD into the FD_ARRAY and pushes the socket event into ARRAY
328 #define PUSH_IP_SOCKET(TYPE, ARRAY, FD_ARRAY, INDEX) \
330 if (-1 != caglobals.ip.TYPE.fd) \
332 INSERT_FD(caglobals.ip.TYPE.fd, FD_ARRAY, INDEX); \
333 PUSH_SOCKET(caglobals.ip.TYPE.fd, ARRAY, INDEX); \
337 #define IS_MATCHING_IP_HANDLE(TYPE, HANDLE, FLAGS) \
338 if ((caglobals.ip.TYPE.fd != -1) && (caglobals.ip.TYPE.fd == HANDLE)) \
340 fd = caglobals.ip.TYPE.fd; \
344 #define EVENT_ARRAY_SIZE 10
346 static void CAFindReadyMessage()
348 int fdArray[EVENT_ARRAY_SIZE];
349 HANDLE eventArray[EVENT_ARRAY_SIZE];
353 // fdArray and eventArray should have same number of elements
354 OC_STATIC_ASSERT(_countof(fdArray) == _countof(eventArray), "Arrays should have same number of elements");
356 PUSH_IP_SOCKET(u6, eventArray, fdArray, arraySize);
357 PUSH_IP_SOCKET(u6s, eventArray, fdArray, arraySize);
358 PUSH_IP_SOCKET(u4, eventArray, fdArray, arraySize);
359 PUSH_IP_SOCKET(u4s, eventArray, fdArray, arraySize);
360 PUSH_IP_SOCKET(m6, eventArray, fdArray, arraySize);
361 PUSH_IP_SOCKET(m6s, eventArray, fdArray, arraySize);
362 PUSH_IP_SOCKET(m4, eventArray, fdArray, arraySize);
363 PUSH_IP_SOCKET(m4s, eventArray, fdArray, arraySize);
365 if (-1 != caglobals.ip.shutdownEvent)
367 INSERT_FD(caglobals.ip.shutdownEvent, fdArray, arraySize);
368 PUSH_HANDLE(caglobals.ip.shutdownEvent, eventArray, arraySize);
371 /** @todo Support netlink events */
373 // Should not have overflowed buffer
374 assert(arraySize <= (_countof(fdArray)));
376 // Timeout is unnecessary on Windows
377 assert(-1 == caglobals.ip.selectTimeout);
379 while (!caglobals.ip.terminate)
381 int ret = WSAWaitForMultipleEvents(arraySize, eventArray, FALSE, WSA_INFINITE, FALSE);
385 case WSA_WAIT_FAILED:
386 OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents returned WSA_WAIT_FAILED 0x%08x", WSAGetLastError());
388 case WSA_WAIT_IO_COMPLETION:
389 OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents returned WSA_WAIT_IO_COMPLETION 0x%08x", WSAGetLastError());
391 case WSA_WAIT_TIMEOUT:
392 OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents returned WSA_WAIT_TIMEOUT 0x%08x", WSAGetLastError());
395 eventIndex = ret - WSA_WAIT_EVENT_0;
396 if ((eventIndex >= 0) && (eventIndex < arraySize))
398 if (false == WSAResetEvent(eventArray[eventIndex]))
400 OIC_LOG_V(ERROR, TAG, "WSAResetEvent failed 0x%08x", WSAGetLastError());
402 CAEventReturned(fdArray[eventIndex]);
406 OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents failed 0x%08x", WSAGetLastError());
413 while (arraySize > 0)
416 if (!WSACloseEvent(eventArray[arraySize]))
418 OIC_LOG_V(ERROR, TAG, "WSACloseEvent (Index %i) failed 0x%08x", arraySize, WSAGetLastError());
423 static void CAEventReturned(HANDLE handle)
426 CATransportFlags_t flags = CA_DEFAULT_FLAGS;
428 while (!caglobals.ip.terminate)
430 IS_MATCHING_IP_HANDLE(u6, handle, CA_IPV6)
431 else IS_MATCHING_IP_HANDLE(u6s, handle, CA_IPV6 | CA_SECURE)
432 else IS_MATCHING_IP_HANDLE(u4, handle, CA_IPV4)
433 else IS_MATCHING_IP_HANDLE(u4s, handle, CA_IPV4 | CA_SECURE)
434 else IS_MATCHING_IP_HANDLE(m6, handle, CA_MULTICAST | CA_IPV6)
435 else IS_MATCHING_IP_HANDLE(m6s, handle, CA_MULTICAST | CA_IPV6 | CA_SECURE)
436 else IS_MATCHING_IP_HANDLE(m4, handle, CA_MULTICAST | CA_IPV4)
437 else IS_MATCHING_IP_HANDLE(m4s, handle, CA_MULTICAST | CA_IPV4 | CA_SECURE)
438 else if ((caglobals.ip.shutdownEvent != -1) && (caglobals.ip.shutdownEvent == handle))
446 (void)CAReceiveMessage(handle, flags);
447 // We will never get more than one match per handle, so always break.
451 if (caglobals.ip.terminate)
453 if (-1 != caglobals.ip.shutdownEvent)
455 // We presume the shutdownEvent will be closed in CAFindReadyMessage
456 caglobals.ip.shutdownEvent = -1;
464 void CADeInitializeIPGlobals()
475 if (caglobals.ip.netlinkFd != -1)
478 closesocket(caglobals.ip.netlinkFd);
480 close(caglobals.ip.netlinkFd);
482 caglobals.ip.netlinkFd = -1;
486 static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags)
488 char recvBuffer[COAP_MAX_PDU_SIZE];
491 int level, type, namelen;
492 struct sockaddr_storage srcAddr;
493 unsigned char *pktinfo = NULL;
494 #if !defined(WSA_CMSG_DATA)
495 struct cmsghdr *cmp = NULL;
496 struct iovec iov = { .iov_base = recvBuffer, .iov_len = sizeof (recvBuffer) };
500 unsigned char data[CMSG_SPACE(sizeof (struct in6_pktinfo))];
505 namelen = sizeof (struct sockaddr_in6);
506 level = IPPROTO_IPV6;
508 len = sizeof (struct in6_pktinfo);
512 namelen = sizeof (struct sockaddr_in);
515 len = sizeof (struct in6_pktinfo);
518 struct msghdr msg = { .msg_name = &srcAddr,
519 .msg_namelen = namelen,
522 .msg_control = &cmsg,
523 .msg_controllen = CMSG_SPACE(len) };
525 ssize_t recvLen = recvmsg(fd, &msg, flags);
528 OIC_LOG_V(ERROR, TAG, "Recvfrom failed %s", strerror(errno));
529 return CA_STATUS_FAILED;
532 if (flags & CA_MULTICAST)
534 for (cmp = CMSG_FIRSTHDR(&msg); cmp != NULL; cmp = CMSG_NXTHDR(&msg, cmp))
536 if (cmp->cmsg_level == level && cmp->cmsg_type == type)
538 pktinfo = CMSG_DATA(cmp);
542 #else // if defined(WSA_CMSG_DATA)
546 uint8_t data[WSA_CMSG_SPACE(sizeof (IN6_PKTINFO))];
548 memset(&cmsg, 0, sizeof(cmsg));
552 namelen = sizeof (struct sockaddr_in6);
553 level = IPPROTO_IPV6;
558 namelen = sizeof (struct sockaddr_in);
563 WSABUF iov = {.len = sizeof (recvBuffer), .buf = recvBuffer};
564 WSAMSG msg = {.name = &srcAddr,
568 .Control = {.buf = cmsg.data, .len = sizeof (cmsg)}
571 uint32_t recvLen = 0;
572 uint32_t ret = caglobals.ip.wsaRecvMsg(fd, &msg, &recvLen, 0,0);
573 OIC_LOG_V(DEBUG, TAG, "WSARecvMsg recvd %u bytes", recvLen);
574 if (SOCKET_ERROR == ret)
576 OIC_LOG_V(ERROR, TAG, "WSARecvMsg failed %i", WSAGetLastError());
579 if (flags & CA_MULTICAST)
581 for (WSACMSGHDR *cmp = WSA_CMSG_FIRSTHDR(&msg); cmp != NULL;
582 cmp = WSA_CMSG_NXTHDR(&msg, cmp))
584 if (cmp->cmsg_level == level && cmp->cmsg_type == type)
586 pktinfo = WSA_CMSG_DATA(cmp);
590 #endif // !defined(WSA_CMSG_DATA)
591 CASecureEndpoint_t sep = {.endpoint = {.adapter = CA_ADAPTER_IP, .flags = flags}};
595 /** @todo figure out correct usage for ifindex, and sin6_scope_id.*/
596 if ((flags & CA_MULTICAST) && pktinfo)
598 struct in6_addr *addr = &(((struct in6_pktinfo *)pktinfo)->ipi6_addr);
599 unsigned char topbits = ((unsigned char *)addr)[0];
602 sep.endpoint.flags &= ~CA_MULTICAST;
608 if ((flags & CA_MULTICAST) && pktinfo)
610 struct in_addr *addr = &((struct in_pktinfo *)pktinfo)->ipi_addr;
611 uint32_t host = ntohl(addr->s_addr);
612 unsigned char topbits = ((unsigned char *)&host)[3];
613 if (topbits < 224 || topbits > 239)
615 sep.endpoint.flags &= ~CA_MULTICAST;
620 CAConvertAddrToName(&srcAddr, namelen, sep.endpoint.addr, &sep.endpoint.port);
622 if (flags & CA_SECURE)
625 int ret = CAAdapterNetDtlsDecrypt(&sep, (uint8_t *)recvBuffer, recvLen);
626 OIC_LOG_V(DEBUG, TAG, "CAAdapterNetDtlsDecrypt returns [%d]", ret);
628 OIC_LOG(ERROR, TAG, "Encrypted message but no DTLS");
633 if (g_packetReceivedCallback)
635 g_packetReceivedCallback(&sep, recvBuffer, recvLen);
645 OIC_LOG(DEBUG, TAG, "IN");
646 OIC_LOG(DEBUG, TAG, "OUT");
649 static int CACreateSocket(int family, uint16_t *port)
651 int socktype = SOCK_DGRAM;
653 socktype |= SOCK_CLOEXEC;
655 int fd = socket(family, socktype, IPPROTO_UDP);
658 OIC_LOG_V(ERROR, TAG, "create socket failed: %s", CAIPS_GET_ERROR);
662 #if !defined(SOCK_CLOEXEC) && defined(FD_CLOEXEC)
663 int fl = fcntl(fd, F_GETFD);
664 if (-1 == fl || -1 == fcntl(fd, F_SETFD, fl|FD_CLOEXEC))
666 OIC_LOG_V(ERROR, TAG, "set FD_CLOEXEC failed: %s", strerror(errno));
671 struct sockaddr_storage sa = { .ss_family = family };
674 if (family == AF_INET6)
678 if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, OPTVAL_T(&on), sizeof (on)))
680 OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", CAIPS_GET_ERROR);
683 if (*port) // only do this for multicast ports
685 #if defined(IPV6_RECVPKTINFO)
686 if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof (on)))
688 if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_PKTINFO, OPTVAL_T(&on), sizeof (on)))
691 OIC_LOG_V(ERROR, TAG, "IPV6_RECVPKTINFO failed: %s",CAIPS_GET_ERROR);
695 ((struct sockaddr_in6 *)&sa)->sin6_port = htons(*port);
696 socklen = sizeof (struct sockaddr_in6);
700 if (*port) // only do this for multicast ports
703 if (-1 == setsockopt(fd, IPPROTO_IP, IP_PKTINFO, OPTVAL_T(&on), sizeof (on)))
705 OIC_LOG_V(ERROR, TAG, "IP_PKTINFO failed: %s", CAIPS_GET_ERROR);
709 ((struct sockaddr_in *)&sa)->sin_port = htons(*port);
710 socklen = sizeof (struct sockaddr_in);
713 if (*port) // use the given port
716 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof (on)))
718 OIC_LOG_V(ERROR, TAG, "SO_REUSEADDR failed: %s", CAIPS_GET_ERROR);
728 if (-1 == bind(fd, (struct sockaddr *)&sa, socklen))
730 OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", CAIPS_GET_ERROR);
739 if (!*port) // return the assigned port
741 if (-1 == getsockname(fd, (struct sockaddr *)&sa, &socklen))
743 OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", CAIPS_GET_ERROR);
751 *port = ntohs(family == AF_INET6 ?
752 ((struct sockaddr_in6 *)&sa)->sin6_port :
753 ((struct sockaddr_in *)&sa)->sin_port);
759 #define CHECKFD(FD) \
760 if (FD > caglobals.ip.maxfd) \
761 caglobals.ip.maxfd = FD;
762 #define NEWSOCKET(FAMILY, NAME) \
763 caglobals.ip.NAME.fd = CACreateSocket(FAMILY, &caglobals.ip.NAME.port); \
764 CHECKFD(caglobals.ip.NAME.fd)
766 static void CAInitializeNetlink()
768 caglobals.ip.netlinkFd = -1;
770 // create NETLINK fd for interface change notifications
771 struct sockaddr_nl sa = { AF_NETLINK, 0, 0, RTMGRP_LINK };
773 caglobals.ip.netlinkFd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC, NETLINK_ROUTE);
774 if (caglobals.ip.netlinkFd == -1)
776 OIC_LOG_V(ERROR, TAG, "netlink socket failed: %s", strerror(errno));
780 int r = bind(caglobals.ip.netlinkFd, (struct sockaddr *)&sa, sizeof (sa));
783 OIC_LOG_V(ERROR, TAG, "netlink bind failed: %s", strerror(errno));
784 close(caglobals.ip.netlinkFd);
785 caglobals.ip.netlinkFd = -1;
789 CHECKFD(caglobals.ip.netlinkFd);
795 static void CAInitializeFastShutdownMechanism()
797 caglobals.ip.selectTimeout = -1; // don't poll for shutdown
799 #if defined(WSA_WAIT_EVENT_0)
800 caglobals.ip.shutdownEvent = -1;
801 caglobals.ip.shutdownEvent = WSACreateEvent();
803 if (caglobals.ip.shutdownEvent == WSA_INVALID_EVENT)
805 caglobals.ip.shutdownEvent = -1;
811 #elif defined(HAVE_PIPE2)
812 ret = pipe2(caglobals.ip.shutdownFds, O_CLOEXEC);
813 CHECKFD(caglobals.ip.shutdownFds[0]);
814 CHECKFD(caglobals.ip.shutdownFds[1]);
816 ret = pipe(caglobals.ip.shutdownFds);
819 ret = fcntl(caglobals.ip.shutdownFds[0], F_GETFD);
822 ret = fcntl(caglobals.ip.shutdownFds[0], F_SETFD, ret|FD_CLOEXEC);
826 ret = fcntl(caglobals.ip.shutdownFds[1], F_GETFD);
830 ret = fcntl(caglobals.ip.shutdownFds[1], F_SETFD, ret|FD_CLOEXEC);
834 close(caglobals.ip.shutdownFds[1]);
835 close(caglobals.ip.shutdownFds[0]);
836 caglobals.ip.shutdownFds[0] = -1;
837 caglobals.ip.shutdownFds[1] = -1;
840 CHECKFD(caglobals.ip.shutdownFds[0]);
841 CHECKFD(caglobals.ip.shutdownFds[1]);
845 OIC_LOG_V(ERROR, TAG, "fast shutdown mechanism init failed: %s", CAIPS_GET_ERROR);
846 caglobals.ip.selectTimeout = SELECT_TIMEOUT; //poll needed for shutdown
850 CAResult_t CAIPStartServer(const ca_thread_pool_t threadPool)
852 CAResult_t res = CA_STATUS_OK;
854 if (caglobals.ip.started)
859 WORD wVersionRequested = MAKEWORD(2, 2);
860 WSADATA wsaData ={.wVersion = 0};
861 int err = WSAStartup(wVersionRequested, &wsaData);
864 OIC_LOG_V(ERROR, TAG, "WSAStartup failed: %i", err);
865 return CA_STATUS_FAILED;
867 OIC_LOG(DEBUG, TAG, "WSAStartup Succeeded");
869 if (!IPv4MulticastAddress.s_addr)
871 (void)inet_pton(AF_INET, IPv4_MULTICAST, &IPv4MulticastAddress);
872 (void)inet_pton(AF_INET6, IPv6_MULTICAST_INT, &IPv6MulticastAddressInt);
873 (void)inet_pton(AF_INET6, IPv6_MULTICAST_LNK, &IPv6MulticastAddressLnk);
874 (void)inet_pton(AF_INET6, IPv6_MULTICAST_RLM, &IPv6MulticastAddressRlm);
875 (void)inet_pton(AF_INET6, IPv6_MULTICAST_ADM, &IPv6MulticastAddressAdm);
876 (void)inet_pton(AF_INET6, IPv6_MULTICAST_SIT, &IPv6MulticastAddressSit);
877 (void)inet_pton(AF_INET6, IPv6_MULTICAST_ORG, &IPv6MulticastAddressOrg);
878 (void)inet_pton(AF_INET6, IPv6_MULTICAST_GLB, &IPv6MulticastAddressGlb);
881 if (!caglobals.ip.ipv6enabled && !caglobals.ip.ipv4enabled)
883 caglobals.ip.ipv4enabled = true; // only needed to run CA tests
886 if (caglobals.ip.ipv6enabled)
888 NEWSOCKET(AF_INET6, u6)
889 NEWSOCKET(AF_INET6, u6s)
890 NEWSOCKET(AF_INET6, m6)
891 NEWSOCKET(AF_INET6, m6s)
892 OIC_LOG_V(INFO, TAG, "IPv6 unicast port: %u", caglobals.ip.u6.port);
894 if (caglobals.ip.ipv4enabled)
896 NEWSOCKET(AF_INET, u4)
897 NEWSOCKET(AF_INET, u4s)
898 NEWSOCKET(AF_INET, m4)
899 NEWSOCKET(AF_INET, m4s)
900 OIC_LOG_V(INFO, TAG, "IPv4 unicast port: %u", caglobals.ip.u4.port);
903 OIC_LOG_V(DEBUG, TAG,
904 "socket summary: u6=%d, u6s=%d, u4=%d, u4s=%d, m6=%d, m6s=%d, m4=%d, m4s=%d",
905 caglobals.ip.u6.fd, caglobals.ip.u6s.fd, caglobals.ip.u4.fd, caglobals.ip.u4s.fd,
906 caglobals.ip.m6.fd, caglobals.ip.m6s.fd, caglobals.ip.m4.fd, caglobals.ip.m4s.fd);
908 OIC_LOG_V(DEBUG, TAG,
909 "port summary: u6 port=%d, u6s port=%d, u4 port=%d, u4s port=%d, m6 port=%d,"
910 "m6s port=%d, m4 port=%d, m4s port=%d",
911 caglobals.ip.u6.port, caglobals.ip.u6s.port, caglobals.ip.u4.port,
912 caglobals.ip.u4s.port, caglobals.ip.m6.port, caglobals.ip.m6s.port,
913 caglobals.ip.m4.port, caglobals.ip.m4s.port);
914 #if defined (SIO_GET_EXTENSION_FUNCTION_POINTER)
915 caglobals.ip.wsaRecvMsg = NULL;
916 GUID GuidWSARecvMsg = WSAID_WSARECVMSG;
918 err = WSAIoctl(caglobals.ip.u4.fd, SIO_GET_EXTENSION_FUNCTION_POINTER, &GuidWSARecvMsg, sizeof(GuidWSARecvMsg), &(caglobals.ip.wsaRecvMsg), sizeof(caglobals.ip.wsaRecvMsg), &copied, 0, 0);
921 OIC_LOG_V(ERROR, TAG, "WSAIoctl failed %i", WSAGetLastError());
922 return CA_STATUS_FAILED;
925 // set up appropriate FD mechanism for fast shutdown
926 CAInitializeFastShutdownMechanism();
928 // create source of network interface change notifications
929 CAInitializeNetlink();
931 caglobals.ip.selectTimeout = CAGetPollingInterval(caglobals.ip.selectTimeout);
933 res = CAIPStartListenServer();
934 if (CA_STATUS_OK != res)
936 OIC_LOG_V(ERROR, TAG, "Failed to start listening server![%d]", res);
940 caglobals.ip.terminate = false;
941 res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
942 if (CA_STATUS_OK != res)
944 OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
947 OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
949 caglobals.ip.started = true;
953 void CAIPStopServer()
955 caglobals.ip.started = false;
956 caglobals.ip.terminate = true;
958 #if !defined(WSA_WAIT_EVENT_0)
959 if (caglobals.ip.shutdownFds[1] != -1)
961 close(caglobals.ip.shutdownFds[1]);
962 // receive thread will stop immediately
966 // receive thread will stop in SELECT_TIMEOUT seconds.
969 if (!WSASetEvent(caglobals.ip.shutdownEvent))
971 OIC_LOG_V(DEBUG, TAG, "set shutdown event failed: %#08X", GetLastError());
976 void CAWakeUpForChange()
978 #if !defined(WSA_WAIT_EVENT_0)
979 if (caglobals.ip.shutdownFds[1] != -1)
984 len = write(caglobals.ip.shutdownFds[1], "w", 1);
985 } while ((len == -1) && (errno == EINTR));
986 if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
988 OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
992 if (!WSASetEvent(caglobals.ip.shutdownEvent))
994 OIC_LOG_V(DEBUG, TAG, "set shutdown event failed: %#08X", GetLastError());
999 static void applyMulticastToInterface4(uint32_t ifindex)
1001 if (!caglobals.ip.ipv4enabled)
1006 #if defined(USE_IP_MREQN)
1007 struct ip_mreqn mreq = { .imr_multiaddr = IPv4MulticastAddress,
1008 .imr_address.s_addr = htonl(INADDR_ANY),
1009 .imr_ifindex = ifindex };
1011 struct ip_mreq mreq = { .imr_multiaddr = IPv4MulticastAddress,
1012 .imr_interface.s_addr = htonl(ifindex) };
1015 int ret = setsockopt(caglobals.ip.m4.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, OPTVAL_T(&mreq), sizeof (mreq));
1018 #if !defined(WSAEINVAL)
1019 if (EADDRINUSE != errno)
1021 if (WSAEINVAL != WSAGetLastError()) // Joining multicast group more than once (IPv4 Flavor)
1024 OIC_LOG_V(ERROR, TAG, " IPv4 IP_ADD_MEMBERSHIP failed: %s", CAIPS_GET_ERROR);
1027 ret = setsockopt(caglobals.ip.m4s.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof (mreq));
1030 #if !defined(WSAEINVAL)
1031 if (EADDRINUSE != errno)
1033 if (WSAEINVAL != WSAGetLastError()) // Joining multicast group more than once (IPv4 Flavor)
1036 OIC_LOG_V(ERROR, TAG, "SECURE IPv4 IP_ADD_MEMBERSHIP failed: %s", CAIPS_GET_ERROR);
1041 static void applyMulticast6(int fd, struct in6_addr *addr, uint32_t ifindex)
1043 struct ipv6_mreq mreq = {.ipv6mr_multiaddr = *addr,
1044 .ipv6mr_interface = ifindex };
1045 int ret = setsockopt(fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq, sizeof (mreq));
1048 #if !defined(_WIN32)
1049 if (EADDRINUSE != errno)
1051 if (WSAEINVAL != WSAGetLastError()) // Joining multicast group more than once (IPv6 Flavor)
1054 OIC_LOG_V(ERROR, TAG, "IPv6 IPV6_JOIN_GROUP failed: %s", CAIPS_GET_ERROR);
1059 static void applyMulticastToInterface6(uint32_t ifindex)
1061 if (!caglobals.ip.ipv6enabled)
1065 //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressInt, ifindex);
1066 applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressLnk, ifindex);
1067 //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressRlm, ifindex);
1068 //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressAdm, ifindex);
1069 //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressSit, ifindex);
1070 //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressOrg, ifindex);
1071 //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressGlb, ifindex);
1073 //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressInt, ifindex);
1074 applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressLnk, ifindex);
1075 //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressRlm, ifindex);
1076 //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressAdm, ifindex);
1077 //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressSit, ifindex);
1078 //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressOrg, ifindex);
1079 //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressGlb, ifindex);
1082 CAResult_t CAIPStartListenServer()
1084 u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
1087 OIC_LOG_V(ERROR, TAG, "CAIPGetInterfaceInformation() failed: %s", strerror(errno));
1088 return CA_STATUS_FAILED;
1091 uint32_t len = u_arraylist_length(iflist);
1092 OIC_LOG_V(DEBUG, TAG, "IP network interfaces found: %d", len);
1094 for (uint32_t i = 0; i < len; i++)
1096 CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1102 if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
1106 if (ifitem->family == AF_INET)
1108 OIC_LOG_V(DEBUG, TAG, "Adding IPv4 interface %i to multicast group", ifitem->index);
1109 applyMulticastToInterface4(ifitem->index);
1111 if (ifitem->family == AF_INET6)
1113 OIC_LOG_V(DEBUG, TAG, "Adding IPv6 interface %i to multicast group", ifitem->index);
1114 applyMulticastToInterface6(ifitem->index);
1118 u_arraylist_destroy(iflist);
1119 return CA_STATUS_OK;
1122 CAResult_t CAIPStopListenServer()
1124 u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
1127 OIC_LOG_V(ERROR, TAG, "Get interface info failed: %s", strerror(errno));
1128 return CA_STATUS_FAILED;
1131 uint32_t len = u_arraylist_length(iflist);
1132 OIC_LOG_V(DEBUG, TAG, "IP network interfaces found: %d", len);
1134 for (uint32_t i = 0; i < len; i++)
1136 CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1142 if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
1146 if (ifitem->family == AF_INET)
1150 OIC_LOG_V(DEBUG, TAG, "IPv4 network interface: %s cloed", ifitem->name);
1152 if (ifitem->family == AF_INET6)
1156 OIC_LOG_V(DEBUG, TAG, "IPv6 network interface: %s", ifitem->name);
1159 u_arraylist_destroy(iflist);
1160 return CA_STATUS_OK;
1163 static void CAProcessNewInterface(CAInterface_t *ifitem)
1167 OIC_LOG(DEBUG, TAG, "ifitem is null");
1171 if (ifitem->family == AF_INET6)
1173 applyMulticastToInterface6(ifitem->index);
1175 if (ifitem->family == AF_INET)
1177 applyMulticastToInterface4(ifitem->index);
1181 void CAIPSetPacketReceiveCallback(CAIPPacketReceivedCallback callback)
1183 g_packetReceivedCallback = callback;
1186 void CAIPSetConnectionStateChangeCallback(CAIPConnectionStateChangeCallback callback)
1188 CAIPSetNetworkMonitorCallback(callback);
1191 static void sendData(int fd, const CAEndpoint_t *endpoint,
1192 const void *data, uint32_t dlen,
1193 const char *cast, const char *fam)
1195 OIC_LOG(DEBUG, TAG, "IN");
1199 OIC_LOG(DEBUG, TAG, "endpoint is null");
1200 if (g_ipErrorHandler)
1202 g_ipErrorHandler(endpoint, data, dlen, CA_STATUS_INVALID_PARAM);
1207 char *secure = (endpoint->flags & CA_SECURE) ? "secure " : "";
1209 (void)cast; // eliminates release warning
1212 struct sockaddr_storage sock;
1213 CAConvertNameToAddr(endpoint->addr, endpoint->port, &sock);
1216 if (sock.ss_family == AF_INET6)
1218 /** @todo figure out correct usage for ifindex, and sin6_scope_id */
1219 socklen = sizeof(struct sockaddr_in6);
1223 socklen = sizeof(struct sockaddr_in);
1225 #if !defined(_WIN32)
1226 ssize_t len = sendto(fd, data, dlen, 0, (struct sockaddr *)&sock, socklen);
1229 // If logging is not defined/enabled.
1230 if (g_ipErrorHandler)
1232 g_ipErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
1234 OIC_LOG_V(ERROR, TAG, "%s%s %s sendTo failed: %s", secure, cast, fam, strerror(errno));
1238 OIC_LOG_V(INFO, TAG, "%s%s %s sendTo is successful: %zd bytes", secure, cast, fam, len);
1245 len = sendto(fd, ((char*)data) + sent, dlen - sent, 0, (struct sockaddr *)&sock, socklen);
1246 if (SOCKET_ERROR == len)
1248 err = WSAGetLastError();
1249 if ((WSAEWOULDBLOCK != err) && (WSAENOBUFS != err))
1251 // If logging is not defined/enabled.
1252 if (g_ipErrorHandler)
1254 g_ipErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
1257 OIC_LOG_V(ERROR, TAG, "%s%s %s sendTo failed: %i", secure, cast, fam, err);
1265 OIC_LOG_V(DEBUG, TAG, "%s%s %s sendTo (Partial Send) is successful: "
1266 "currently sent: %ld bytes, "
1267 "total sent: %ld bytes, "
1268 "remaining: %ld bytes",
1269 secure, cast, fam, len, sent, dlen-sent);
1273 OIC_LOG_V(INFO, TAG, "%s%s %s sendTo is successful: %ld bytes",
1274 secure, cast, fam, len);
1277 } while ((SOCKET_ERROR == len) && ((WSAEWOULDBLOCK == err) || (WSAENOBUFS == err)) || (sent < dlen));
1281 static void sendMulticastData6(const u_arraylist_t *iflist,
1282 CAEndpoint_t *endpoint,
1283 const void *data, uint32_t datalen)
1287 OIC_LOG(DEBUG, TAG, "endpoint is null");
1291 int scope = endpoint->flags & CA_SCOPE_MASK;
1292 char *ipv6mcname = ipv6mcnames[scope];
1295 OIC_LOG_V(INFO, TAG, "IPv6 multicast scope invalid: %d", scope);
1298 OICStrcpy(endpoint->addr, sizeof(endpoint->addr), ipv6mcname);
1299 int fd = caglobals.ip.u6.fd;
1301 uint32_t len = u_arraylist_length(iflist);
1302 for (uint32_t i = 0; i < len; i++)
1304 CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1309 if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
1313 if (ifitem->family != AF_INET6)
1318 int index = ifitem->index;
1319 if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, OPTVAL_T(&index), sizeof (index)))
1321 OIC_LOG_V(ERROR, TAG, "setsockopt6 failed: %s", CAIPS_GET_ERROR);
1324 sendData(fd, endpoint, data, datalen, "multicast", "ipv6");
1328 static void sendMulticastData4(const u_arraylist_t *iflist,
1329 CAEndpoint_t *endpoint,
1330 const void *data, uint32_t datalen)
1332 VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
1334 #if defined(USE_IP_MREQN)
1335 struct ip_mreqn mreq = { .imr_multiaddr = IPv4MulticastAddress,
1336 .imr_address.s_addr = htonl(INADDR_ANY),
1339 struct ip_mreq mreq = { .imr_multiaddr = IPv4MulticastAddress,
1340 .imr_interface = {0}};
1343 OICStrcpy(endpoint->addr, sizeof(endpoint->addr), IPv4_MULTICAST);
1344 int fd = caglobals.ip.u4.fd;
1346 uint32_t len = u_arraylist_length(iflist);
1347 for (uint32_t i = 0; i < len; i++)
1349 CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1354 if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
1358 if (ifitem->family != AF_INET)
1362 #if defined(USE_IP_MREQN)
1363 mreq.imr_ifindex = ifitem->index;
1365 mreq.imr_interface.s_addr = htonl(ifitem->index);
1367 if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, OPTVAL_T(&mreq), sizeof (mreq)))
1369 OIC_LOG_V(ERROR, TAG, "send IP_MULTICAST_IF failed: %s (using defualt)",
1372 sendData(fd, endpoint, data, datalen, "multicast", "ipv4");
1376 void CAIPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
1379 VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
1380 VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
1382 bool isSecure = (endpoint->flags & CA_SECURE) != 0;
1386 endpoint->port = isSecure ? CA_SECURE_COAP : CA_COAP;
1388 u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
1391 OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
1395 if ((endpoint->flags & CA_IPV6) && caglobals.ip.ipv6enabled)
1397 sendMulticastData6(iflist, endpoint, data, datalen);
1399 if ((endpoint->flags & CA_IPV4) && caglobals.ip.ipv4enabled)
1401 sendMulticastData4(iflist, endpoint, data, datalen);
1404 u_arraylist_destroy(iflist);
1408 if (!endpoint->port) // unicast discovery
1410 endpoint->port = isSecure ? CA_SECURE_COAP : CA_COAP;
1414 if (caglobals.ip.ipv6enabled && (endpoint->flags & CA_IPV6))
1416 fd = isSecure ? caglobals.ip.u6s.fd : caglobals.ip.u6.fd;
1417 #ifndef __WITH_DTLS__
1418 fd = caglobals.ip.u6.fd;
1420 sendData(fd, endpoint, data, datalen, "unicast", "ipv6");
1422 if (caglobals.ip.ipv4enabled && (endpoint->flags & CA_IPV4))
1424 fd = isSecure ? caglobals.ip.u4s.fd : caglobals.ip.u4.fd;
1425 #ifndef __WITH_DTLS__
1426 fd = caglobals.ip.u4.fd;
1428 sendData(fd, endpoint, data, datalen, "unicast", "ipv4");
1433 CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1435 VERIFY_NON_NULL(info, TAG, "info is NULL");
1436 VERIFY_NON_NULL(size, TAG, "size is NULL");
1438 u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
1441 OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
1442 return CA_STATUS_FAILED;
1445 uint32_t len = u_arraylist_length(iflist);
1446 uint32_t length = len;
1448 #ifdef __WITH_DTLS__
1449 //If DTLS is supported, each interface can support secure port as well
1453 CAEndpoint_t *eps = (CAEndpoint_t *)OICCalloc(length, sizeof (CAEndpoint_t));
1456 OIC_LOG(ERROR, TAG, "Malloc Failed");
1457 u_arraylist_destroy(iflist);
1458 return CA_MEMORY_ALLOC_FAILED;
1461 for (uint32_t i = 0, j = 0; i < len; i++)
1463 CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1469 eps[j].adapter = CA_ADAPTER_IP;
1472 if (ifitem->family == AF_INET6)
1474 eps[j].flags = CA_IPV6;
1475 eps[j].port = caglobals.ip.u6.port;
1479 eps[j].flags = CA_IPV4;
1480 eps[j].port = caglobals.ip.u4.port;
1481 /** @todo eps[j].addr not populated with IPv4 address string.
1482 * it was using ifitem->ipv4addr to accomplish this.
1483 * Need to understand what ipv4addr means to whom*/
1486 #ifdef __WITH_DTLS__
1489 eps[j].adapter = CA_ADAPTER_IP;
1492 if (ifitem->family == AF_INET6)
1494 eps[j].flags = CA_IPV6 | CA_SECURE;
1495 eps[j].port = caglobals.ip.u6s.port;
1499 eps[j].flags = CA_IPV4 | CA_SECURE;
1500 eps[j].port = caglobals.ip.u4s.port;
1501 inet_ntop(AF_INET, &(ifitem->ipv4addr), eps[j].addr, MAX_ADDR_STR_SIZE_CA);
1510 u_arraylist_destroy(iflist);
1512 return CA_STATUS_OK;
1515 void CAIPSetErrorHandler(CAIPErrorHandleCallback errorHandleCallback)
1517 g_ipErrorHandler = errorHandleCallback;