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>
43 #include <sys/types.h>
46 #include <sys/select.h>
47 #include <arpa/inet.h>
48 #include <netinet/in.h>
53 #include <linux/netlink.h>
54 #include <linux/rtnetlink.h>
58 #include "caipinterface.h"
59 #include "caadapterutils.h"
61 #include "caadapternetdtls.h"
64 #include "oic_malloc.h"
65 #include "oic_string.h"
73 * Logging tag for module name
75 #define TAG "OIC_CA_IP_SERVER"
77 #define SELECT_TIMEOUT 1 // select() seconds (and termination latency)
79 #define IPv4_MULTICAST "224.0.1.187"
80 static struct in_addr IPv4MulticastAddress = { 0 };
82 #define IPv6_DOMAINS 16
83 #define IPv6_MULTICAST_INT "ff01::fd"
84 static struct in6_addr IPv6MulticastAddressInt;
85 #define IPv6_MULTICAST_LNK "ff02::fd"
86 static struct in6_addr IPv6MulticastAddressLnk;
87 #define IPv6_MULTICAST_RLM "ff03::fd"
88 static struct in6_addr IPv6MulticastAddressRlm;
89 #define IPv6_MULTICAST_ADM "ff04::fd"
90 static struct in6_addr IPv6MulticastAddressAdm;
91 #define IPv6_MULTICAST_SIT "ff05::fd"
92 static struct in6_addr IPv6MulticastAddressSit;
93 #define IPv6_MULTICAST_ORG "ff08::fd"
94 static struct in6_addr IPv6MulticastAddressOrg;
95 #define IPv6_MULTICAST_GLB "ff0e::fd"
96 static struct in6_addr IPv6MulticastAddressGlb;
98 static char *ipv6mcnames[IPv6_DOMAINS] = {
118 #define IFF_UP_RUNNING_FLAGS (IFF_UP)
120 char* caips_get_error(){
121 static char buffer[32];
122 snprintf(buffer, 32, "%i", WSAGetLastError());
125 #define CAIPS_GET_ERROR \
128 #define IFF_UP_RUNNING_FLAGS (IFF_UP|IFF_RUNNING)
130 #define CAIPS_GET_ERROR \
133 static CAIPExceptionCallback g_exceptionCallback;
135 static CAIPPacketReceivedCallback g_packetReceivedCallback;
137 static void CAHandleNetlink();
138 static void CAFindReadyMessage();
139 #if !defined(WSA_WAIT_EVENT_0)
140 static void CASelectReturned(fd_set *readFds, int ret);
142 static void CAEventReturned(HANDLE);
144 static void CAProcessNewInterface(CAInterface_t *ifchanged);
145 static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags);
147 static void CAReceiveHandler(void *data)
151 while (!caglobals.ip.terminate)
153 CAFindReadyMessage();
157 #if !defined(WSA_WAIT_EVENT_0)
159 #define CLOSE_SOCKET(TYPE) \
160 if (caglobals.ip.TYPE.fd != -1) \
162 close(caglobals.ip.TYPE.fd); \
163 caglobals.ip.TYPE.fd = -1; \
166 #define SET(TYPE, FDS) \
167 if (caglobals.ip.TYPE.fd != -1) \
169 FD_SET(caglobals.ip.TYPE.fd, FDS); \
172 #define ISSET(TYPE, FDS, FLAGS) \
173 if (caglobals.ip.TYPE.fd != -1 && FD_ISSET(caglobals.ip.TYPE.fd, FDS)) \
175 fd = caglobals.ip.TYPE.fd; \
180 static void CAFindReadyMessage()
183 struct timeval timeout;
185 timeout.tv_sec = caglobals.ip.selectTimeout;
187 struct timeval *tv = caglobals.ip.selectTimeout == -1 ? NULL : &timeout;
199 if (caglobals.ip.shutdownFds[0] != -1)
201 FD_SET(caglobals.ip.shutdownFds[0], &readFds);
203 if (caglobals.ip.netlinkFd != -1)
205 FD_SET(caglobals.ip.netlinkFd, &readFds);
208 int ret = select(caglobals.ip.maxfd + 1, &readFds, NULL, NULL, tv);
210 if (caglobals.ip.terminate)
212 OIC_LOG_V(DEBUG, TAG, "Packet receiver Stop request received.");
220 OIC_LOG_V(FATAL, TAG, "select error %s", CAIPS_GET_ERROR);
225 CASelectReturned(&readFds, ret);
228 static void CASelectReturned(fd_set *readFds, int ret)
232 CATransportFlags_t flags = CA_DEFAULT_FLAGS;
234 while (!caglobals.ip.terminate)
236 ISSET(u6, readFds, CA_IPV6)
237 else ISSET(u6s, readFds, CA_IPV6 | CA_SECURE)
238 else ISSET(u4, readFds, CA_IPV4)
239 else ISSET(u4s, readFds, CA_IPV4 | CA_SECURE)
240 else ISSET(m6, readFds, CA_MULTICAST | CA_IPV6)
241 else ISSET(m6s, readFds, CA_MULTICAST | CA_IPV6 | CA_SECURE)
242 else ISSET(m4, readFds, CA_MULTICAST | CA_IPV4)
243 else ISSET(m4s, readFds, CA_MULTICAST | CA_IPV4 | CA_SECURE)
244 else if ((caglobals.ip.netlinkFd != -1) && FD_ISSET(caglobals.ip.netlinkFd, readFds))
246 CAInterface_t *ifchanged = CAFindInterfaceChange();
249 CAProcessNewInterface(ifchanged);
254 else if (FD_ISSET(caglobals.ip.shutdownFds[0], readFds))
257 ssize_t len = read(caglobals.ip.shutdownFds[0], buf, sizeof (buf));
268 (void)CAReceiveMessage(fd, flags);
273 #else // if defined(WSA_WAIT_EVENT_0)
275 #define CLOSE_SOCKET(TYPE) \
276 if (caglobals.ip.TYPE.fd != -1) \
278 closesocket(caglobals.ip.TYPE.fd); \
279 caglobals.ip.TYPE.fd = -1; \
282 #define PUSH_HANDLE(HANDLE, ARRAY, INDEX) \
284 ARRAY[INDEX] = HANDLE; \
288 // Turn handle into WSAEvent and push to ARRAY
289 #define PUSH_SOCKET(SOCKET, ARRAY, INDEX) \
293 NewEvent = WSACreateEvent(); \
294 if (WSA_INVALID_EVENT != NewEvent) \
296 if (0 != WSAEventSelect(SOCKET, NewEvent, FD_READ)) \
298 OIC_LOG_V(ERROR, TAG, "WSAEventSelect failed 0x%08x ", WSAGetLastError()); \
299 if (!WSACloseEvent(NewEvent)) \
301 OIC_LOG_V(ERROR, TAG, "WSACloseEvent(NewEvent) failed 0x%08x", WSAGetLastError()); \
306 PUSH_HANDLE(NewEvent, ARRAY, INDEX); \
311 OIC_LOG_V(ERROR, TAG, "WSACreateEvent(NewEvent) failed 0x%08x", WSAGetLastError()); \
315 #define INSERT_FD(FD, ARRAY, INDEX) \
324 // Inserts the FD into the FD_ARRAY and pushes the socket event into ARRAY
325 #define PUSH_IP_SOCKET(TYPE, ARRAY, FD_ARRAY, INDEX) \
327 if (-1 != caglobals.ip.TYPE.fd) \
329 INSERT_FD(caglobals.ip.TYPE.fd, FD_ARRAY, INDEX); \
330 PUSH_SOCKET(caglobals.ip.TYPE.fd, ARRAY, INDEX); \
334 #define IS_MATCHING_IP_HANDLE(TYPE, HANDLE, FLAGS) \
335 if ((caglobals.ip.TYPE.fd != -1) && (caglobals.ip.TYPE.fd == HANDLE)) \
337 fd = caglobals.ip.TYPE.fd; \
341 #define EVENT_ARRAY_SIZE 10
343 static void CAFindReadyMessage()
345 int fdArray[EVENT_ARRAY_SIZE];
346 HANDLE eventArray[EVENT_ARRAY_SIZE];
350 // fdArray and eventArray should have same number of elements
351 /** @todo: replace with OC_STATIC_ASSERT */
352 _Static_assert(_countof(fdArray) == _countof(eventArray), "Arrays should have same number of elements");
354 PUSH_IP_SOCKET(u6, eventArray, fdArray, arraySize);
355 PUSH_IP_SOCKET(u6s, eventArray, fdArray, arraySize);
356 PUSH_IP_SOCKET(u4, eventArray, fdArray, arraySize);
357 PUSH_IP_SOCKET(u4s, eventArray, fdArray, arraySize);
358 PUSH_IP_SOCKET(m6, eventArray, fdArray, arraySize);
359 PUSH_IP_SOCKET(m6s, eventArray, fdArray, arraySize);
360 PUSH_IP_SOCKET(m4, eventArray, fdArray, arraySize);
361 PUSH_IP_SOCKET(m4s, eventArray, fdArray, arraySize);
363 if (-1 != caglobals.ip.shutdownEvent)
365 INSERT_FD(caglobals.ip.shutdownEvent, fdArray, arraySize);
366 PUSH_HANDLE(caglobals.ip.shutdownEvent, eventArray, arraySize);
369 /** @todo Support netlink events */
371 // Should not have overflowed buffer
372 assert(arraySize <= (_countof(fdArray)));
374 // Timeout is unnecessary on Windows
375 assert(-1 == caglobals.ip.selectTimeout);
377 while (!caglobals.ip.terminate)
379 int ret = WSAWaitForMultipleEvents(arraySize, eventArray, FALSE, WSA_INFINITE, FALSE);
383 case WSA_WAIT_FAILED:
384 OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents returned WSA_WAIT_FAILED 0x%08x", WSAGetLastError());
386 case WSA_WAIT_IO_COMPLETION:
387 OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents returned WSA_WAIT_IO_COMPLETION 0x%08x", WSAGetLastError());
389 case WSA_WAIT_TIMEOUT:
390 OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents returned WSA_WAIT_TIMEOUT 0x%08x", WSAGetLastError());
393 eventIndex = ret - WSA_WAIT_EVENT_0;
394 if ((eventIndex >= 0) && (eventIndex < arraySize))
396 if (false == WSAResetEvent(eventArray[eventIndex]))
398 OIC_LOG_V(ERROR, TAG, "WSAResetEvent failed 0x%08x", WSAGetLastError());
400 CAEventReturned(fdArray[eventIndex]);
404 OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents failed 0x%08x", WSAGetLastError());
411 while (arraySize > 0)
414 if (!WSACloseEvent(eventArray[arraySize]))
416 OIC_LOG_V(ERROR, TAG, "WSACloseEvent (Index %i) failed 0x%08x", arraySize, WSAGetLastError());
421 static void CAEventReturned(HANDLE handle)
424 CATransportFlags_t flags = CA_DEFAULT_FLAGS;
426 while (!caglobals.ip.terminate)
428 IS_MATCHING_IP_HANDLE(u6, handle, CA_IPV6)
429 else IS_MATCHING_IP_HANDLE(u6s, handle, CA_IPV6 | CA_SECURE)
430 else IS_MATCHING_IP_HANDLE(u4, handle, CA_IPV4)
431 else IS_MATCHING_IP_HANDLE(u4s, handle, CA_IPV4 | CA_SECURE)
432 else IS_MATCHING_IP_HANDLE(m6, handle, CA_MULTICAST | CA_IPV6)
433 else IS_MATCHING_IP_HANDLE(m6s, handle, CA_MULTICAST | CA_IPV6 | CA_SECURE)
434 else IS_MATCHING_IP_HANDLE(m4, handle, CA_MULTICAST | CA_IPV4)
435 else IS_MATCHING_IP_HANDLE(m4s, handle, CA_MULTICAST | CA_IPV4 | CA_SECURE)
436 else if ((caglobals.ip.shutdownEvent != -1) && (caglobals.ip.shutdownEvent == handle))
444 (void)CAReceiveMessage(handle, flags);
445 // We will never get more than one match per handle, so always break.
449 if (caglobals.ip.terminate)
451 if (-1 != caglobals.ip.shutdownEvent)
453 // We presume the shutdownEvent will be closed in CAFindReadyMessage
454 caglobals.ip.shutdownEvent = -1;
462 void CADeInitializeIPGlobals()
473 if (caglobals.ip.netlinkFd != -1)
476 closesocket(caglobals.ip.netlinkFd);
478 close(caglobals.ip.netlinkFd);
480 caglobals.ip.netlinkFd = -1;
484 static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags)
486 char recvBuffer[COAP_MAX_PDU_SIZE];
489 int level, type, namelen;
490 struct sockaddr_storage srcAddr;
491 unsigned char *pktinfo = NULL;
492 #if !defined(WSA_CMSG_DATA)
493 struct cmsghdr *cmp = NULL;
494 struct iovec iov = { .iov_base = recvBuffer, .iov_len = sizeof (recvBuffer) };
498 unsigned char data[CMSG_SPACE(sizeof (struct in6_pktinfo))];
503 namelen = sizeof (struct sockaddr_in6);
504 level = IPPROTO_IPV6;
506 len = sizeof (struct in6_pktinfo);
510 namelen = sizeof (struct sockaddr_in);
513 len = sizeof (struct in6_pktinfo);
516 struct msghdr msg = { .msg_name = &srcAddr,
517 .msg_namelen = namelen,
520 .msg_control = &cmsg,
521 .msg_controllen = CMSG_SPACE(len) };
523 ssize_t recvLen = recvmsg(fd, &msg, flags);
526 OIC_LOG_V(ERROR, TAG, "Recvfrom failed %s", strerror(errno));
527 return CA_STATUS_FAILED;
530 if (flags & CA_MULTICAST)
532 for (cmp = CMSG_FIRSTHDR(&msg); cmp != NULL; cmp = CMSG_NXTHDR(&msg, cmp))
534 if (cmp->cmsg_level == level && cmp->cmsg_type == type)
536 pktinfo = CMSG_DATA(cmp);
540 #else // if defined(WSA_CMSG_DATA)
544 uint8_t data[WSA_CMSG_SPACE(sizeof (IN6_PKTINFO))];
546 memset(&cmsg, 0, sizeof(cmsg));
550 namelen = sizeof (struct sockaddr_in6);
551 level = IPPROTO_IPV6;
556 namelen = sizeof (struct sockaddr_in);
561 WSABUF iov = {.len = sizeof (recvBuffer), .buf = recvBuffer};
562 WSAMSG msg = {.name = &srcAddr,
566 .Control = {.buf = cmsg.data, .len = sizeof (cmsg)}
569 uint32_t recvLen = 0;
570 uint32_t ret = caglobals.ip.wsaRecvMsg(fd, &msg, &recvLen, 0,0);
571 OIC_LOG_V(DEBUG, TAG, "WSARecvMsg recvd %u bytes", recvLen);
572 if (SOCKET_ERROR == ret)
574 OIC_LOG_V(ERROR, TAG, "WSARecvMsg failed %i", WSAGetLastError());
577 if (flags & CA_MULTICAST)
579 for (WSACMSGHDR *cmp = WSA_CMSG_FIRSTHDR(&msg); cmp != NULL;
580 cmp = WSA_CMSG_NXTHDR(&msg, cmp))
582 if (cmp->cmsg_level == level && cmp->cmsg_type == type)
584 pktinfo = WSA_CMSG_DATA(cmp);
588 #endif // !defined(WSA_CMSG_DATA)
589 CASecureEndpoint_t sep = {.endpoint = {.adapter = CA_ADAPTER_IP, .flags = flags}};
593 /** @todo figure out correct usage for ifindex, and sin6_scope_id.*/
594 if ((flags & CA_MULTICAST) && pktinfo)
596 struct in6_addr *addr = &(((struct in6_pktinfo *)pktinfo)->ipi6_addr);
597 unsigned char topbits = ((unsigned char *)addr)[0];
600 sep.endpoint.flags &= ~CA_MULTICAST;
606 if ((flags & CA_MULTICAST) && pktinfo)
608 struct in_addr *addr = &((struct in_pktinfo *)pktinfo)->ipi_addr;
609 uint32_t host = ntohl(addr->s_addr);
610 unsigned char topbits = ((unsigned char *)&host)[3];
611 if (topbits < 224 || topbits > 239)
613 sep.endpoint.flags &= ~CA_MULTICAST;
618 CAConvertAddrToName(&srcAddr, namelen, sep.endpoint.addr, &sep.endpoint.port);
620 if (flags & CA_SECURE)
623 int ret = CAAdapterNetDtlsDecrypt(&sep, (uint8_t *)recvBuffer, recvLen);
624 OIC_LOG_V(DEBUG, TAG, "CAAdapterNetDtlsDecrypt returns [%d]", ret);
626 OIC_LOG(ERROR, TAG, "Encrypted message but no DTLS");
631 if (g_packetReceivedCallback)
633 g_packetReceivedCallback(&sep, recvBuffer, recvLen);
643 OIC_LOG(DEBUG, TAG, "IN");
644 OIC_LOG(DEBUG, TAG, "OUT");
647 static int CACreateSocket(int family, uint16_t *port)
649 int socktype = SOCK_DGRAM;
651 socktype |= SOCK_CLOEXEC;
653 int fd = socket(family, socktype, IPPROTO_UDP);
656 OIC_LOG_V(ERROR, TAG, "create socket failed: %s", CAIPS_GET_ERROR);
660 #if !defined(SOCK_CLOEXEC) && defined(FD_CLOEXEC)
661 int fl = fcntl(fd, F_GETFD);
662 if (-1 == fl || -1 == fcntl(fd, F_SETFD, fl|FD_CLOEXEC))
664 OIC_LOG_V(ERROR, TAG, "set FD_CLOEXEC failed: %s", strerror(errno));
669 struct sockaddr_storage sa = { .ss_family = family };
672 if (family == AF_INET6)
676 if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
678 OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", CAIPS_GET_ERROR);
681 if (*port) // only do this for multicast ports
683 #if defined(IPV6_RECVPKTINFO)
684 if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof (on)))
686 if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_PKTINFO, &on, sizeof (on)))
689 OIC_LOG_V(ERROR, TAG, "IPV6_RECVPKTINFO failed: %s",CAIPS_GET_ERROR);
693 ((struct sockaddr_in6 *)&sa)->sin6_port = htons(*port);
694 socklen = sizeof (struct sockaddr_in6);
698 if (*port) // only do this for multicast ports
701 if (-1 == setsockopt(fd, IPPROTO_IP, IP_PKTINFO, &on, sizeof (on)))
703 OIC_LOG_V(ERROR, TAG, "IP_PKTINFO failed: %s", CAIPS_GET_ERROR);
707 ((struct sockaddr_in *)&sa)->sin_port = htons(*port);
708 socklen = sizeof (struct sockaddr_in);
711 if (*port) // use the given port
714 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof (on)))
716 OIC_LOG_V(ERROR, TAG, "SO_REUSEADDR failed: %s", CAIPS_GET_ERROR);
726 if (-1 == bind(fd, (struct sockaddr *)&sa, socklen))
728 OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", CAIPS_GET_ERROR);
737 if (!*port) // return the assigned port
739 if (-1 == getsockname(fd, (struct sockaddr *)&sa, &socklen))
741 OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", CAIPS_GET_ERROR);
749 *port = ntohs(family == AF_INET6 ?
750 ((struct sockaddr_in6 *)&sa)->sin6_port :
751 ((struct sockaddr_in *)&sa)->sin_port);
757 #define CHECKFD(FD) \
758 if (FD > caglobals.ip.maxfd) \
759 caglobals.ip.maxfd = FD;
760 #define NEWSOCKET(FAMILY, NAME) \
761 caglobals.ip.NAME.fd = CACreateSocket(FAMILY, &caglobals.ip.NAME.port); \
762 CHECKFD(caglobals.ip.NAME.fd)
764 static void CAInitializeNetlink()
766 caglobals.ip.netlinkFd = -1;
768 // create NETLINK fd for interface change notifications
769 struct sockaddr_nl sa = { AF_NETLINK, 0, 0, RTMGRP_LINK };
771 caglobals.ip.netlinkFd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC, NETLINK_ROUTE);
772 if (caglobals.ip.netlinkFd == -1)
774 OIC_LOG_V(ERROR, TAG, "netlink socket failed: %s", strerror(errno));
778 int r = bind(caglobals.ip.netlinkFd, (struct sockaddr *)&sa, sizeof (sa));
781 OIC_LOG_V(ERROR, TAG, "netlink bind failed: %s", strerror(errno));
782 close(caglobals.ip.netlinkFd);
783 caglobals.ip.netlinkFd = -1;
787 CHECKFD(caglobals.ip.netlinkFd);
793 static void CAInitializeFastShutdownMechanism()
795 caglobals.ip.selectTimeout = -1; // don't poll for shutdown
797 #if defined(WSA_WAIT_EVENT_0)
798 caglobals.ip.shutdownEvent = -1;
799 caglobals.ip.shutdownEvent = WSACreateEvent();
801 if (caglobals.ip.shutdownEvent == WSA_INVALID_EVENT)
803 caglobals.ip.shutdownEvent = -1;
809 #elif defined(HAVE_PIPE2)
810 ret = pipe2(caglobals.ip.shutdownFds, O_CLOEXEC);
811 CHECKFD(caglobals.ip.shutdownFds[0]);
812 CHECKFD(caglobals.ip.shutdownFds[1]);
814 ret = pipe(caglobals.ip.shutdownFds);
817 ret = fcntl(caglobals.ip.shutdownFds[0], F_GETFD);
820 ret = fcntl(caglobals.ip.shutdownFds[0], F_SETFD, ret|FD_CLOEXEC);
824 ret = fcntl(caglobals.ip.shutdownFds[1], F_GETFD);
828 ret = fcntl(caglobals.ip.shutdownFds[1], F_SETFD, ret|FD_CLOEXEC);
832 close(caglobals.ip.shutdownFds[1]);
833 close(caglobals.ip.shutdownFds[0]);
834 caglobals.ip.shutdownFds[0] = -1;
835 caglobals.ip.shutdownFds[1] = -1;
838 CHECKFD(caglobals.ip.shutdownFds[0]);
839 CHECKFD(caglobals.ip.shutdownFds[1]);
843 OIC_LOG_V(ERROR, TAG, "fast shutdown mechanism init failed: %s", CAIPS_GET_ERROR);
844 caglobals.ip.selectTimeout = SELECT_TIMEOUT; //poll needed for shutdown
848 CAResult_t CAIPStartServer(const ca_thread_pool_t threadPool)
850 CAResult_t res = CA_STATUS_OK;
852 if (caglobals.ip.started)
857 WORD wVersionRequested = MAKEWORD(2, 2);
858 WSADATA wsaData ={.wVersion = 0};
859 int err = WSAStartup(wVersionRequested, &wsaData);
862 OIC_LOG_V(ERROR, TAG, "WSAStartup failed: %i", err);
863 return CA_STATUS_FAILED;
865 OIC_LOG(DEBUG, TAG, "WSAStartup Succeeded");
867 if (!IPv4MulticastAddress.s_addr)
869 (void)inet_pton(AF_INET, IPv4_MULTICAST, &IPv4MulticastAddress);
870 (void)inet_pton(AF_INET6, IPv6_MULTICAST_INT, &IPv6MulticastAddressInt);
871 (void)inet_pton(AF_INET6, IPv6_MULTICAST_LNK, &IPv6MulticastAddressLnk);
872 (void)inet_pton(AF_INET6, IPv6_MULTICAST_RLM, &IPv6MulticastAddressRlm);
873 (void)inet_pton(AF_INET6, IPv6_MULTICAST_ADM, &IPv6MulticastAddressAdm);
874 (void)inet_pton(AF_INET6, IPv6_MULTICAST_SIT, &IPv6MulticastAddressSit);
875 (void)inet_pton(AF_INET6, IPv6_MULTICAST_ORG, &IPv6MulticastAddressOrg);
876 (void)inet_pton(AF_INET6, IPv6_MULTICAST_GLB, &IPv6MulticastAddressGlb);
879 if (!caglobals.ip.ipv6enabled && !caglobals.ip.ipv4enabled)
881 caglobals.ip.ipv4enabled = true; // only needed to run CA tests
884 if (caglobals.ip.ipv6enabled)
886 NEWSOCKET(AF_INET6, u6)
887 NEWSOCKET(AF_INET6, u6s)
888 NEWSOCKET(AF_INET6, m6)
889 NEWSOCKET(AF_INET6, m6s)
890 OIC_LOG_V(INFO, TAG, "IPv6 unicast port: %u", caglobals.ip.u6.port);
892 if (caglobals.ip.ipv4enabled)
894 NEWSOCKET(AF_INET, u4)
895 NEWSOCKET(AF_INET, u4s)
896 NEWSOCKET(AF_INET, m4)
897 NEWSOCKET(AF_INET, m4s)
898 OIC_LOG_V(INFO, TAG, "IPv4 unicast port: %u", caglobals.ip.u4.port);
901 OIC_LOG_V(DEBUG, TAG,
902 "socket summary: u6=%d, u6s=%d, u4=%d, u4s=%d, m6=%d, m6s=%d, m4=%d, m4s=%d",
903 caglobals.ip.u6.fd, caglobals.ip.u6s.fd, caglobals.ip.u4.fd, caglobals.ip.u4s.fd,
904 caglobals.ip.m6.fd, caglobals.ip.m6s.fd, caglobals.ip.m4.fd, caglobals.ip.m4s.fd);
906 OIC_LOG_V(DEBUG, TAG,
907 "port summary: u6 port=%d, u6s port=%d, u4 port=%d, u4s port=%d, m6 port=%d,"
908 "m6s port=%d, m4 port=%d, m4s port=%d",
909 caglobals.ip.u6.port, caglobals.ip.u6s.port, caglobals.ip.u4.port,
910 caglobals.ip.u4s.port, caglobals.ip.m6.port, caglobals.ip.m6s.port,
911 caglobals.ip.m4.port, caglobals.ip.m4s.port);
912 #if defined (SIO_GET_EXTENSION_FUNCTION_POINTER)
913 caglobals.ip.wsaRecvMsg = NULL;
914 GUID GuidWSARecvMsg = WSAID_WSARECVMSG;
916 err = WSAIoctl(caglobals.ip.u4.fd, SIO_GET_EXTENSION_FUNCTION_POINTER, &GuidWSARecvMsg, sizeof(GuidWSARecvMsg), &(caglobals.ip.wsaRecvMsg), sizeof(caglobals.ip.wsaRecvMsg), &copied, 0, 0);
919 OIC_LOG_V(ERROR, TAG, "WSAIoctl failed %i", WSAGetLastError());
920 return CA_STATUS_FAILED;
923 // set up appropriate FD mechanism for fast shutdown
924 CAInitializeFastShutdownMechanism();
926 // create source of network interface change notifications
927 CAInitializeNetlink();
929 caglobals.ip.selectTimeout = CAGetPollingInterval(caglobals.ip.selectTimeout);
931 res = CAIPStartListenServer();
932 if (CA_STATUS_OK != res)
934 OIC_LOG_V(ERROR, TAG, "Failed to start listening server![%d]", res);
938 caglobals.ip.terminate = false;
939 res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
940 if (CA_STATUS_OK != res)
942 OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
945 OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
947 caglobals.ip.started = true;
951 void CAIPStopServer()
953 caglobals.ip.started = false;
954 caglobals.ip.terminate = true;
956 #if !defined(WSA_WAIT_EVENT_0)
957 if (caglobals.ip.shutdownFds[1] != -1)
959 close(caglobals.ip.shutdownFds[1]);
960 // receive thread will stop immediately
964 // receive thread will stop in SELECT_TIMEOUT seconds.
967 if (!WSASetEvent(caglobals.ip.shutdownEvent))
969 OIC_LOG_V(DEBUG, TAG, "set shutdown event failed: %#08X", GetLastError());
974 void CAWakeUpForChange()
976 #if !defined(WSA_WAIT_EVENT_0)
977 if (caglobals.ip.shutdownFds[1] != -1)
982 len = write(caglobals.ip.shutdownFds[1], "w", 1);
983 } while ((len == -1) && (errno == EINTR));
984 if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
986 OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
990 if (!WSASetEvent(caglobals.ip.shutdownEvent))
992 OIC_LOG_V(DEBUG, TAG, "set shutdown event failed: %#08X", GetLastError());
997 static void applyMulticastToInterface4(uint32_t ifindex)
999 if (!caglobals.ip.ipv4enabled)
1004 #if defined(USE_IP_MREQN)
1005 struct ip_mreqn mreq = { .imr_multiaddr = IPv4MulticastAddress,
1006 .imr_address.s_addr = htonl(INADDR_ANY),
1007 .imr_ifindex = ifindex };
1009 struct ip_mreq mreq = { .imr_multiaddr = IPv4MulticastAddress,
1010 .imr_interface.s_addr = htonl(ifindex) };
1013 int ret = setsockopt(caglobals.ip.m4.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof (mreq));
1016 #if !defined(WSAEINVAL)
1017 if (EADDRINUSE != errno)
1019 if (WSAEINVAL != WSAGetLastError()) // Joining multicast group more than once (IPv4 Flavor)
1022 OIC_LOG_V(ERROR, TAG, " IPv4 IP_ADD_MEMBERSHIP failed: %s", CAIPS_GET_ERROR);
1025 ret = setsockopt(caglobals.ip.m4s.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof (mreq));
1028 #if !defined(WSAEINVAL)
1029 if (EADDRINUSE != errno)
1031 if (WSAEINVAL != WSAGetLastError()) // Joining multicast group more than once (IPv4 Flavor)
1034 OIC_LOG_V(ERROR, TAG, "SECURE IPv4 IP_ADD_MEMBERSHIP failed: %s", CAIPS_GET_ERROR);
1039 static void applyMulticast6(int fd, struct in6_addr *addr, uint32_t ifindex)
1041 struct ipv6_mreq mreq = {.ipv6mr_multiaddr = *addr,
1042 .ipv6mr_interface = ifindex };
1043 int ret = setsockopt(fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq, sizeof (mreq));
1046 #if !defined(_WIN32)
1047 if (EADDRINUSE != errno)
1049 if (WSAEINVAL != WSAGetLastError()) // Joining multicast group more than once (IPv6 Flavor)
1052 OIC_LOG_V(ERROR, TAG, "IPv6 IPV6_JOIN_GROUP failed: %s", CAIPS_GET_ERROR);
1057 static void applyMulticastToInterface6(uint32_t ifindex)
1059 if (!caglobals.ip.ipv6enabled)
1063 //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressInt, ifindex);
1064 applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressLnk, ifindex);
1065 //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressRlm, ifindex);
1066 //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressAdm, ifindex);
1067 //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressSit, ifindex);
1068 //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressOrg, ifindex);
1069 //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressGlb, ifindex);
1071 //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressInt, ifindex);
1072 applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressLnk, ifindex);
1073 //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressRlm, ifindex);
1074 //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressAdm, ifindex);
1075 //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressSit, ifindex);
1076 //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressOrg, ifindex);
1077 //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressGlb, ifindex);
1080 CAResult_t CAIPStartListenServer()
1082 u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
1085 OIC_LOG_V(ERROR, TAG, "CAIPGetInterfaceInformation() failed: %s", strerror(errno));
1086 return CA_STATUS_FAILED;
1089 uint32_t len = u_arraylist_length(iflist);
1090 OIC_LOG_V(DEBUG, TAG, "IP network interfaces found: %d", len);
1092 for (uint32_t i = 0; i < len; i++)
1094 CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1100 if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
1104 if (ifitem->family == AF_INET)
1106 OIC_LOG_V(DEBUG, TAG, "Adding IPv4 interface %i to multicast group", ifitem->index);
1107 applyMulticastToInterface4(ifitem->index);
1109 if (ifitem->family == AF_INET6)
1111 OIC_LOG_V(DEBUG, TAG, "Adding IPv6 interface %i to multicast group", ifitem->index);
1112 applyMulticastToInterface6(ifitem->index);
1116 u_arraylist_destroy(iflist);
1117 return CA_STATUS_OK;
1120 CAResult_t CAIPStopListenServer()
1122 u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
1125 OIC_LOG_V(ERROR, TAG, "Get interface info failed: %s", strerror(errno));
1126 return CA_STATUS_FAILED;
1129 uint32_t len = u_arraylist_length(iflist);
1130 OIC_LOG_V(DEBUG, TAG, "IP network interfaces found: %d", len);
1132 for (uint32_t i = 0; i < len; i++)
1134 CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1140 if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
1144 if (ifitem->family == AF_INET)
1148 OIC_LOG_V(DEBUG, TAG, "IPv4 network interface: %s cloed", ifitem->name);
1150 if (ifitem->family == AF_INET6)
1154 OIC_LOG_V(DEBUG, TAG, "IPv6 network interface: %s", ifitem->name);
1157 u_arraylist_destroy(iflist);
1158 return CA_STATUS_OK;
1161 static void CAProcessNewInterface(CAInterface_t *ifitem)
1165 OIC_LOG(DEBUG, TAG, "ifitem is null");
1169 if (ifitem->family == AF_INET6)
1171 applyMulticastToInterface6(ifitem->index);
1173 if (ifitem->family == AF_INET)
1175 applyMulticastToInterface4(ifitem->index);
1179 void CAIPSetPacketReceiveCallback(CAIPPacketReceivedCallback callback)
1181 g_packetReceivedCallback = callback;
1184 void CAIPSetExceptionCallback(CAIPExceptionCallback callback)
1186 g_exceptionCallback = callback;
1189 void CAIPSetConnectionStateChangeCallback(CAIPConnectionStateChangeCallback callback)
1191 CAIPSetNetworkMonitorCallback(callback);
1194 static void sendData(int fd, const CAEndpoint_t *endpoint,
1195 const void *data, uint32_t dlen,
1196 const char *cast, const char *fam)
1198 OIC_LOG(DEBUG, TAG, "IN");
1202 OIC_LOG(DEBUG, TAG, "endpoint is null");
1206 char *secure = (endpoint->flags & CA_SECURE) ? "secure " : "";
1208 (void)secure; // 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 OIC_LOG_V(ERROR, TAG, "%s%s %s sendTo failed: %s", secure, cast, fam, strerror(errno));
1233 OIC_LOG_V(INFO, TAG, "%s%s %s sendTo is successful: %zd bytes", secure, cast, fam, len);
1240 len = sendto(fd, ((char*)data) + sent, dlen - sent, 0, (struct sockaddr *)&sock, socklen);
1241 if (SOCKET_ERROR == len)
1243 err = WSAGetLastError();
1244 if ((WSAEWOULDBLOCK != err) && (WSAENOBUFS != err))
1246 OIC_LOG_V(ERROR, TAG, "%s%s %s sendTo failed: %i", secure, cast, fam, err);
1254 OIC_LOG_V(DEBUG, TAG, "%s%s %s sendTo (Partial Send) is successful: "
1255 "currently sent: %ld bytes, "
1256 "total sent: %ld bytes, "
1257 "remaining: %ld bytes",
1258 secure, cast, fam, len, sent, dlen-sent);
1262 OIC_LOG_V(INFO, TAG, "%s%s %s sendTo is successful: %ld bytes",
1263 secure, cast, fam, len);
1266 } while ((SOCKET_ERROR == len) && ((WSAEWOULDBLOCK == err) || (WSAENOBUFS == err)) || (sent < dlen));
1270 static void sendMulticastData6(const u_arraylist_t *iflist,
1271 CAEndpoint_t *endpoint,
1272 const void *data, uint32_t datalen)
1276 OIC_LOG(DEBUG, TAG, "endpoint is null");
1280 int scope = endpoint->flags & CA_SCOPE_MASK;
1281 char *ipv6mcname = ipv6mcnames[scope];
1284 OIC_LOG_V(INFO, TAG, "IPv6 multicast scope invalid: %d", scope);
1287 OICStrcpy(endpoint->addr, sizeof(endpoint->addr), ipv6mcname);
1288 int fd = caglobals.ip.u6.fd;
1290 uint32_t len = u_arraylist_length(iflist);
1291 for (uint32_t i = 0; i < len; i++)
1293 CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1298 if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
1302 if (ifitem->family != AF_INET6)
1307 int index = ifitem->index;
1308 if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, &index, sizeof (index)))
1310 OIC_LOG_V(ERROR, TAG, "setsockopt6 failed: %s", CAIPS_GET_ERROR);
1313 sendData(fd, endpoint, data, datalen, "multicast", "ipv6");
1317 static void sendMulticastData4(const u_arraylist_t *iflist,
1318 CAEndpoint_t *endpoint,
1319 const void *data, uint32_t datalen)
1321 VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
1323 #if defined(USE_IP_MREQN)
1324 struct ip_mreqn mreq = { .imr_multiaddr = IPv4MulticastAddress,
1325 .imr_address.s_addr = htonl(INADDR_ANY),
1328 struct ip_mreq mreq = { .imr_multiaddr = IPv4MulticastAddress,
1329 .imr_interface = {0}};
1332 OICStrcpy(endpoint->addr, sizeof(endpoint->addr), IPv4_MULTICAST);
1333 int fd = caglobals.ip.u4.fd;
1335 uint32_t len = u_arraylist_length(iflist);
1336 for (uint32_t i = 0; i < len; i++)
1338 CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1343 if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
1347 if (ifitem->family != AF_INET)
1351 #if defined(USE_IP_MREQN)
1352 mreq.imr_ifindex = ifitem->index;
1354 mreq.imr_interface.s_addr = htonl(ifitem->index);
1356 if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, &mreq, sizeof (mreq)))
1358 OIC_LOG_V(ERROR, TAG, "send IP_MULTICAST_IF failed: %s (using defualt)",
1361 sendData(fd, endpoint, data, datalen, "multicast", "ipv4");
1365 void CAIPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
1368 VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
1369 VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
1371 bool isSecure = (endpoint->flags & CA_SECURE) != 0;
1375 endpoint->port = isSecure ? CA_SECURE_COAP : CA_COAP;
1377 u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
1380 OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
1384 if ((endpoint->flags & CA_IPV6) && caglobals.ip.ipv6enabled)
1386 sendMulticastData6(iflist, endpoint, data, datalen);
1388 if ((endpoint->flags & CA_IPV4) && caglobals.ip.ipv4enabled)
1390 sendMulticastData4(iflist, endpoint, data, datalen);
1393 u_arraylist_destroy(iflist);
1397 if (!endpoint->port) // unicast discovery
1399 endpoint->port = isSecure ? CA_SECURE_COAP : CA_COAP;
1403 if (caglobals.ip.ipv6enabled && (endpoint->flags & CA_IPV6))
1405 fd = isSecure ? caglobals.ip.u6s.fd : caglobals.ip.u6.fd;
1406 #ifndef __WITH_DTLS__
1407 fd = caglobals.ip.u6.fd;
1409 sendData(fd, endpoint, data, datalen, "unicast", "ipv6");
1411 if (caglobals.ip.ipv4enabled && (endpoint->flags & CA_IPV4))
1413 fd = isSecure ? caglobals.ip.u4s.fd : caglobals.ip.u4.fd;
1414 #ifndef __WITH_DTLS__
1415 fd = caglobals.ip.u4.fd;
1417 sendData(fd, endpoint, data, datalen, "unicast", "ipv4");
1422 CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1424 VERIFY_NON_NULL(info, TAG, "info is NULL");
1425 VERIFY_NON_NULL(size, TAG, "size is NULL");
1427 u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
1430 OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
1431 return CA_STATUS_FAILED;
1434 uint32_t len = u_arraylist_length(iflist);
1435 uint32_t length = len;
1437 #ifdef __WITH_DTLS__
1438 //If DTLS is supported, each interface can support secure port as well
1442 CAEndpoint_t *eps = (CAEndpoint_t *)OICCalloc(length, sizeof (CAEndpoint_t));
1445 OIC_LOG(ERROR, TAG, "Malloc Failed");
1446 u_arraylist_destroy(iflist);
1447 return CA_MEMORY_ALLOC_FAILED;
1450 for (uint32_t i = 0, j = 0; i < len; i++)
1452 CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1458 eps[j].adapter = CA_ADAPTER_IP;
1461 if (ifitem->family == AF_INET6)
1463 eps[j].flags = CA_IPV6;
1464 eps[j].port = caglobals.ip.u6.port;
1468 eps[j].flags = CA_IPV4;
1469 eps[j].port = caglobals.ip.u4.port;
1470 /** @todo eps[j].addr not populated with IPv4 address string.
1471 * it was using ifitem->ipv4addr to accomplish this.
1472 * Need to understand what ipv4addr means to whom*/
1475 #ifdef __WITH_DTLS__
1478 eps[j].adapter = CA_ADAPTER_IP;
1481 if (ifitem->family == AF_INET6)
1483 eps[j].flags = CA_IPV6 | CA_SECURE;
1484 eps[j].port = caglobals.ip.u6s.port;
1488 eps[j].flags = CA_IPV4 | CA_SECURE;
1489 eps[j].port = caglobals.ip.u4s.port;
1490 inet_ntop(AF_INET, &(ifitem->ipv4addr), eps[j].addr, MAX_ADDR_STR_SIZE_CA);
1499 u_arraylist_destroy(iflist);
1501 return CA_STATUS_OK;