[Win32] Rename 'interface' to satisfy Windows.h
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / ip_adapter / caipserver.c
index 7ee0f4b..faec8f8 100644 (file)
  *
  ******************************************************************/
 
-#include "caipinterface.h"
-
-#ifndef __APPLE__
-#include <asm/types.h>
-#else
-    #ifndef IPV6_ADD_MEMBERSHIP
-        #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
-    #endif
+#ifndef __APPLE_USE_RFC_3542
+#define __APPLE_USE_RFC_3542 // for PKTINFO
+#endif
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE // for in6_pktinfo
 #endif
+
 #include <sys/types.h>
 #include <sys/socket.h>
 #include <stdio.h>
@@ -44,6 +42,7 @@
 #endif
 
 #include "pdu.h"
+#include "caipinterface.h"
 #include "caadapterutils.h"
 #ifdef __WITH_DTLS__
 #include "caadapternetdtls.h"
 #include "oic_malloc.h"
 #include "oic_string.h"
 
-/**
- * @def TAG
- * @brief Logging tag for module name
+/*
+ * Logging tag for module name
  */
-#define TAG "IP_SERVER"
+#define TAG "OIC_CA_IP_SERVER"
 
 #define SELECT_TIMEOUT 1     // select() seconds (and termination latency)
 
@@ -103,9 +101,9 @@ static CAIPExceptionCallback g_exceptionCallback;
 static CAIPPacketReceivedCallback g_packetReceivedCallback;
 
 static void CAHandleNetlink();
-static void CAApplyInterfaces();
 static void CAFindReadyMessage();
 static void CASelectReturned(fd_set *readFds, int ret);
+static void CAProcessNewInterface(CAInterface_t *ifchanged);
 static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags);
 
 #define SET(TYPE, FDS) \
@@ -121,17 +119,71 @@ static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags);
         flags = FLAGS; \
     }
 
+void CADeInitializeIPGlobals()
+{
+    if (caglobals.ip.u6.fd != -1)
+    {
+        close(caglobals.ip.u6.fd);
+        caglobals.ip.u6.fd = -1;
+    }
+
+    if (caglobals.ip.u6s.fd != -1)
+    {
+        close(caglobals.ip.u6s.fd);
+        caglobals.ip.u6s.fd = -1;
+    }
+
+    if (caglobals.ip.u4.fd != -1)
+    {
+        close(caglobals.ip.u4.fd);
+        caglobals.ip.u4.fd = -1;
+    }
+
+    if (caglobals.ip.u4s.fd != -1)
+    {
+        close(caglobals.ip.u4s.fd);
+        caglobals.ip.u4s.fd = -1;
+    }
+
+    if (caglobals.ip.m6.fd != -1)
+    {
+        close(caglobals.ip.m6.fd);
+        caglobals.ip.m6.fd = -1;
+    }
+
+    if (caglobals.ip.m6s.fd != -1)
+    {
+        close(caglobals.ip.m6s.fd);
+        caglobals.ip.m6s.fd = -1;
+    }
+
+    if (caglobals.ip.m4.fd != -1)
+    {
+        close(caglobals.ip.m4.fd);
+        caglobals.ip.m4.fd = -1;
+    }
+
+    if (caglobals.ip.m4s.fd != -1)
+    {
+        close(caglobals.ip.m4s.fd);
+        caglobals.ip.m4s.fd = -1;
+    }
+
+    if (caglobals.ip.netlinkFd != -1)
+    {
+        close(caglobals.ip.netlinkFd);
+        caglobals.ip.netlinkFd = -1;
+    }
+}
+
 static void CAReceiveHandler(void *data)
 {
     (void)data;
-    OIC_LOG(DEBUG, TAG, "IN");
 
     while (!caglobals.ip.terminate)
     {
         CAFindReadyMessage();
     }
-
-    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 static void CAFindReadyMessage()
@@ -198,7 +250,22 @@ static void CASelectReturned(fd_set *readFds, int ret)
         else ISSET(m4s, readFds, CA_MULTICAST | CA_IPV4 | CA_SECURE)
         else if (FD_ISSET(caglobals.ip.netlinkFd, readFds))
         {
-            CAHandleNetlink();
+            CAInterface_t *ifchanged = CAFindInterfaceChange();
+            if (ifchanged)
+            {
+                CAProcessNewInterface(ifchanged);
+                OICFree(ifchanged);
+            }
+            break;
+        }
+        else if (FD_ISSET(caglobals.ip.shutdownFds[0], readFds))
+        {
+            char buf[10] = {0};
+            ssize_t len = read(caglobals.ip.shutdownFds[0], buf, sizeof (buf));
+            if (-1 == len)
+            {
+                continue;
+            }
             break;
         }
         else
@@ -215,35 +282,95 @@ static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags)
 {
     char recvBuffer[COAP_MAX_PDU_SIZE];
 
+    size_t len;
+    int level, type, namelen;
     struct sockaddr_storage srcAddr;
-    socklen_t srcAddrLen = sizeof (srcAddr);
-
-    ssize_t recvLen = recvfrom(fd,
-                               recvBuffer,
-                               sizeof (recvBuffer),
-                               0,
-                               (struct sockaddr *)&srcAddr,
-                               &srcAddrLen);
+    unsigned char *pktinfo = NULL;
+    struct cmsghdr *cmp = NULL;
+    struct iovec iov = { recvBuffer, sizeof (recvBuffer) };
+    union control
+    {
+        struct cmsghdr cmsg;
+        unsigned char data[CMSG_SPACE(sizeof (struct in6_pktinfo))];
+    } cmsg;
+
+    if (flags & CA_IPV6)
+    {
+        namelen = sizeof (struct sockaddr_in6);
+        level = IPPROTO_IPV6;
+        type = IPV6_PKTINFO;
+        len = sizeof (struct in6_pktinfo);
+    }
+    else
+    {
+        namelen = sizeof (struct sockaddr_in);
+        level = IPPROTO_IP;
+        type = IP_PKTINFO;
+        len = sizeof (struct in6_pktinfo);
+    }
+
+    struct msghdr msg = { .msg_name = &srcAddr,
+                          .msg_namelen = namelen,
+                          .msg_iov = &iov,
+                          .msg_iovlen = 1,
+                          .msg_control = &cmsg,
+                          .msg_controllen = CMSG_SPACE(len) };
+
+    ssize_t recvLen = recvmsg(fd, &msg, flags);
     if (-1 == recvLen)
     {
         OIC_LOG_V(ERROR, TAG, "Recvfrom failed %s", strerror(errno));
         return CA_STATUS_FAILED;
     }
 
-    CAEndpoint_t ep = { .adapter = CA_ADAPTER_IP,
-                        .flags = flags };
+    if (flags & CA_MULTICAST)
+    {
+        for (cmp = CMSG_FIRSTHDR(&msg); cmp != NULL; cmp = CMSG_NXTHDR(&msg, cmp))
+        {
+            if (cmp->cmsg_level == level && cmp->cmsg_type == type)
+            {
+                pktinfo = CMSG_DATA(cmp);
+            }
+        }
+    }
+
+    CASecureEndpoint_t sep = {.endpoint = {.adapter = CA_ADAPTER_IP, .flags = flags}};
 
     if (flags & CA_IPV6)
     {
-        ep.interface = ((struct sockaddr_in6 *)&srcAddr)->sin6_scope_id;
+        sep.endpoint.ifindex = ((struct sockaddr_in6 *)&srcAddr)->sin6_scope_id;
         ((struct sockaddr_in6 *)&srcAddr)->sin6_scope_id = 0;
+
+        if ((flags & CA_MULTICAST) && pktinfo)
+        {
+            struct in6_addr *addr = &(((struct in6_pktinfo *)pktinfo)->ipi6_addr);
+            unsigned char topbits = ((unsigned char *)addr)[0];
+            if (topbits != 0xff)
+            {
+                sep.endpoint.flags &= ~CA_MULTICAST;
+            }
+        }
+    }
+    else
+    {
+        if ((flags & CA_MULTICAST) && pktinfo)
+        {
+            struct in_addr *addr = &((struct in_pktinfo *)pktinfo)->ipi_addr;
+            uint32_t host = ntohl(addr->s_addr);
+            unsigned char topbits = ((unsigned char *)&host)[3];
+            if (topbits < 224 || topbits > 239)
+            {
+                sep.endpoint.flags &= ~CA_MULTICAST;
+            }
+        }
     }
-    CAConvertAddrToName(&srcAddr, ep.addr, &ep.port);
+
+    CAConvertAddrToName(&srcAddr, msg.msg_namelen, sep.endpoint.addr, &sep.endpoint.port);
 
     if (flags & CA_SECURE)
     {
 #ifdef __WITH_DTLS__
-        int ret = CAAdapterNetDtlsDecrypt(&ep, (uint8_t *)recvBuffer, recvLen);
+        int ret = CAAdapterNetDtlsDecrypt(&sep, (uint8_t *)recvBuffer, recvLen);
         OIC_LOG_V(DEBUG, TAG, "CAAdapterNetDtlsDecrypt returns [%d]", ret);
 #else
         OIC_LOG(ERROR, TAG, "Encrypted message but no DTLS");
@@ -253,7 +380,7 @@ static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags)
     {
         if (g_packetReceivedCallback)
         {
-            g_packetReceivedCallback(&ep, recvBuffer, recvLen);
+            g_packetReceivedCallback(&sep, recvBuffer, recvLen);
         }
     }
 
@@ -269,9 +396,9 @@ void CAIPPullData()
 static int CACreateSocket(int family, uint16_t *port)
 {
     int socktype = SOCK_DGRAM;
-    #ifdef SOCK_CLOEXEC
+#ifdef SOCK_CLOEXEC
     socktype |= SOCK_CLOEXEC;
-    #endif
+#endif
     int fd = socket(family, socktype, IPPROTO_UDP);
     if (-1 == fd)
     {
@@ -279,7 +406,7 @@ static int CACreateSocket(int family, uint16_t *port)
         return -1;
     }
 
-    #ifndef SOCK_CLOEXEC
+#ifndef SOCK_CLOEXEC
     int fl = fcntl(fd, F_GETFD);
     if (-1 == fl || -1 == fcntl(fd, F_SETFD, fl|FD_CLOEXEC))
     {
@@ -287,7 +414,7 @@ static int CACreateSocket(int family, uint16_t *port)
         close(fd);
         return -1;
     }
-    #endif
+#endif
 
     struct sockaddr_storage sa = { .ss_family = family };
     socklen_t socklen;
@@ -295,15 +422,34 @@ static int CACreateSocket(int family, uint16_t *port)
     if (family == AF_INET6)
     {
         int on = 1;
+
         if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
         {
             OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
         }
+
+        if (*port)      // only do this for multicast ports
+        {
+            if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof (on)))
+            {
+                OIC_LOG_V(ERROR, TAG, "IPV6_RECVPKTINFO failed: %s", strerror(errno));
+            }
+        }
+
         ((struct sockaddr_in6 *)&sa)->sin6_port = htons(*port);
         socklen = sizeof (struct sockaddr_in6);
     }
     else
     {
+        if (*port)      // only do this for multicast ports
+        {
+            int on = 1;
+            if (-1 == setsockopt(fd, IPPROTO_IP, IP_PKTINFO, &on, sizeof (on)))
+            {
+                OIC_LOG_V(ERROR, TAG, "IP_PKTINFO failed: %s", strerror(errno));
+            }
+        }
+
         ((struct sockaddr_in *)&sa)->sin_port = htons(*port);
         socklen = sizeof (struct sockaddr_in);
     }
@@ -426,7 +572,7 @@ CAResult_t CAIPStartServer(const ca_thread_pool_t threadPool)
 
     if (!IPv4MulticastAddress.s_addr)
     {
-        (void)inet_aton(IPv4_MULTICAST, &IPv4MulticastAddress);
+        (void)inet_pton(AF_INET, IPv4_MULTICAST, &IPv4MulticastAddress);
         (void)inet_pton(AF_INET6, IPv6_MULTICAST_INT, &IPv6MulticastAddressInt);
         (void)inet_pton(AF_INET6, IPv6_MULTICAST_LNK, &IPv6MulticastAddressLnk);
         (void)inet_pton(AF_INET6, IPv6_MULTICAST_RLM, &IPv6MulticastAddressRlm);
@@ -460,11 +606,15 @@ CAResult_t CAIPStartServer(const ca_thread_pool_t threadPool)
 
     OIC_LOG_V(DEBUG, TAG,
               "socket summary: u6=%d, u6s=%d, u4=%d, u4s=%d, m6=%d, m6s=%d, m4=%d, m4s=%d",
-                             caglobals.ip.u6.fd, caglobals.ip.u6s.fd,
-                             caglobals.ip.u4.fd, caglobals.ip.u4s.fd,
-                             caglobals.ip.m6.fd, caglobals.ip.m6s.fd,
-                             caglobals.ip.m4.fd, caglobals.ip.m4s.fd);
+              caglobals.ip.u6.fd, caglobals.ip.u6s.fd, caglobals.ip.u4.fd, caglobals.ip.u4s.fd,
+              caglobals.ip.m6.fd, caglobals.ip.m6s.fd, caglobals.ip.m4.fd, caglobals.ip.m4s.fd);
 
+    OIC_LOG_V(DEBUG, TAG,
+              "port summary: u6 port=%d, u6s port=%d, u4 port=%d, u4s port=%d, m6 port=%d,"
+              "m6s port=%d, m4 port=%d, m4s port=%d",
+              caglobals.ip.u6.port, caglobals.ip.u6s.port, caglobals.ip.u4.port,
+              caglobals.ip.u4s.port, caglobals.ip.m6.port, caglobals.ip.m6s.port,
+              caglobals.ip.m4.port, caglobals.ip.m4s.port);
     // create pipe for fast shutdown
     CAInitializePipe();
     CHECKFD(caglobals.ip.shutdownFds[0]);
@@ -473,7 +623,14 @@ CAResult_t CAIPStartServer(const ca_thread_pool_t threadPool)
     // create source of network interface change notifications
     CAInitializeNetlink();
 
-    CAApplyInterfaces();
+    caglobals.ip.selectTimeout = CAGetPollingInterval(caglobals.ip.selectTimeout);
+
+    res = CAIPStartListenServer();
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG_V(ERROR, TAG, "Failed to start listening server![%d]", res);
+        return res;
+    }
 
     caglobals.ip.terminate = false;
     res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
@@ -490,8 +647,7 @@ CAResult_t CAIPStartServer(const ca_thread_pool_t threadPool)
 
 void CAIPStopServer()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
+    caglobals.ip.started = false;
     caglobals.ip.terminate = true;
 
     if (caglobals.ip.shutdownFds[1] != -1)
@@ -503,8 +659,22 @@ void CAIPStopServer()
     {
         // receive thread will stop in SELECT_TIMEOUT seconds.
     }
+}
 
-    OIC_LOG(DEBUG, TAG, "OUT");
+void CAWakeUpForChange()
+{
+    if (caglobals.ip.shutdownFds[1] != -1)
+    {
+        ssize_t len = 0;
+        do
+        {
+            len = write(caglobals.ip.shutdownFds[1], "w", 1);
+        } while ((len == -1) && (errno == EINTR));
+        if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
+        {
+            OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
+        }
+    }
 }
 
 static void applyMulticastToInterface4(struct in_addr inaddr)
@@ -514,8 +684,9 @@ static void applyMulticastToInterface4(struct in_addr inaddr)
         return;
     }
 
-    struct ip_mreq mreq = { .imr_multiaddr = IPv4MulticastAddress,
-                            .imr_interface = inaddr};
+    struct ip_mreqn mreq = { .imr_multiaddr = IPv4MulticastAddress,
+                             .imr_address = inaddr,
+                             .imr_ifindex = 0 };
     if (setsockopt(caglobals.ip.m4.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof (mreq)))
     {
         if (EADDRINUSE != errno)
@@ -532,12 +703,10 @@ static void applyMulticastToInterface4(struct in_addr inaddr)
     }
 }
 
-static void applyMulticast6(int fd, struct in6_addr *addr, uint32_t interface)
+static void applyMulticast6(int fd, struct in6_addr *addr, uint32_t ifindex)
 {
-    struct ipv6_mreq mreq;
-    mreq.ipv6mr_multiaddr = *addr;
-    mreq.ipv6mr_interface = interface;
-    if (setsockopt(fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq, sizeof (mreq)))
+    struct ipv6_mreq mreq = {.ipv6mr_multiaddr = *addr, .ipv6mr_interface = ifindex};
+    if (setsockopt(fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq, sizeof (mreq)))
     {
         if (EADDRINUSE != errno)
         {
@@ -546,35 +715,36 @@ static void applyMulticast6(int fd, struct in6_addr *addr, uint32_t interface)
     }
 }
 
-static void applyMulticastToInterface6(uint32_t interface)
+static void applyMulticastToInterface6(uint32_t ifindex)
 {
     if (!caglobals.ip.ipv6enabled)
     {
         return;
     }
-    //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressInt, interface);
-    applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressLnk, interface);
-    //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressRlm, interface);
-    //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressAdm, interface);
-    //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressSit, interface);
-    //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressOrg, interface);
-    //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressGlb, interface);
-    //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressInt, interface);
-    applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressLnk, interface);
-    //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressRlm, interface);
-    //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressAdm, interface);
-    //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressSit, interface);
-    //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressOrg, interface);
-    //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressGlb, interface);
+    //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressInt, ifindex);
+    applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressLnk, ifindex);
+    //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressRlm, ifindex);
+    //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressAdm, ifindex);
+    //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressSit, ifindex);
+    //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressOrg, ifindex);
+    //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressGlb, ifindex);
+
+    //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressInt, ifindex);
+    applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressLnk, ifindex);
+    //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressRlm, ifindex);
+    //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressAdm, ifindex);
+    //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressSit, ifindex);
+    //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressOrg, ifindex);
+    //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressGlb, ifindex);
 }
 
-static void CAApplyInterfaces()
+CAResult_t CAIPStartListenServer()
 {
     u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
     if (!iflist)
     {
         OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
-        return;
+        return CA_STATUS_FAILED;
     }
 
     uint32_t len = u_arraylist_length(iflist);
@@ -607,80 +777,89 @@ static void CAApplyInterfaces()
     }
 
     u_arraylist_destroy(iflist);
+    return CA_STATUS_OK;
 }
 
-static void CAHandleNetlink()
+CAResult_t CAIPStopListenServer()
 {
-#ifdef __linux__
-    char buf[4096];
-    struct nlmsghdr *nh;
-    struct sockaddr_nl sa;
-    struct iovec iov = { buf, sizeof(buf) };
-    struct msghdr msg = { (void *)&sa, sizeof(sa), &iov, 1, NULL, 0, 0 };
+    u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
+    if (!iflist)
+    {
+        OIC_LOG_V(ERROR, TAG, "Get interface info failed: %s", strerror(errno));
+        return CA_STATUS_FAILED;
+    }
 
-    size_t len = recvmsg(caglobals.ip.netlinkFd, &msg, 0);
+    uint32_t len = u_arraylist_length(iflist);
+    OIC_LOG_V(DEBUG, TAG, "IP network interfaces found: %d", len);
 
-    for (nh = (struct nlmsghdr *)buf; NLMSG_OK(nh, len); nh = NLMSG_NEXT(nh, len))
+    for (uint32_t i = 0; i < len; i++)
     {
-        if (nh->nlmsg_type == RTM_NEWLINK)
-        {
-            struct ifinfomsg *ifi = (struct ifinfomsg *)NLMSG_DATA(nh);
-            if ((ifi->ifi_flags & IFF_LOOPBACK) || !(ifi->ifi_flags & IFF_RUNNING))
-            {
-                continue;
-            }
-
-            int newIndex = ifi->ifi_index;
+        CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
 
-            u_arraylist_t *iflist = CAIPGetInterfaceInformation(newIndex);
-            if (!iflist)
-            {
-                OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
-                return;
-            }
+        if (!ifitem)
+        {
+            continue;
+        }
 
-            uint32_t listLength = u_arraylist_length(iflist);
-            for (uint32_t i = 0; i < listLength; i++)
-            {
-                CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
-                if (!ifitem)
-                {
-                    continue;
-                }
-
-                if ((int)ifitem->index != newIndex)
-                {
-                    continue;
-                }
-
-                applyMulticastToInterface6(newIndex);
-                struct in_addr inaddr;
-                inaddr.s_addr = ifitem->ipv4addr;
-                applyMulticastToInterface4(inaddr);
-                break; // we found the one we were looking for
-            }
-            u_arraylist_destroy(iflist);
+        if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
+        {
+            continue;
+        }
+        if (ifitem->family == AF_INET)
+        {
+            close(caglobals.ip.m4.fd);
+            close(caglobals.ip.m4s.fd);
+            caglobals.ip.m4.fd = -1;
+            caglobals.ip.m4s.fd = -1;
+            OIC_LOG_V(DEBUG, TAG, "IPv4 network interface: %s cloed", ifitem->name);
+        }
+        if (ifitem->family == AF_INET6)
+        {
+            close(caglobals.ip.m6.fd);
+            close(caglobals.ip.m6s.fd);
+            caglobals.ip.m6.fd = -1;
+            caglobals.ip.m6s.fd = -1;
+            OIC_LOG_V(DEBUG, TAG, "IPv6 network interface: %s", ifitem->name);
         }
     }
-#endif // __linux__
+    u_arraylist_destroy(iflist);
+    return CA_STATUS_OK;
 }
 
-void CAIPSetPacketReceiveCallback(CAIPPacketReceivedCallback callback)
+static void CAProcessNewInterface(CAInterface_t *ifitem)
 {
-OIC_LOG(DEBUG, TAG, "IN");
-
-g_packetReceivedCallback = callback;
+    if (!ifitem)
+    {
+        OIC_LOG(DEBUG, TAG, "ifitem is null");
+        return;
+    }
+    if (ifitem->family == AF_INET6)
+    {
+        applyMulticastToInterface6(ifitem->index);
+    }
+    if (ifitem->family == AF_INET)
+    {
+        struct in_addr inaddr = { .s_addr = ifitem->ipv4addr };
+        applyMulticastToInterface4(inaddr);
+    }
+}
+static void CAHandleNetlink()
+{
+}
 
-OIC_LOG(DEBUG, TAG, "OUT");
+void CAIPSetPacketReceiveCallback(CAIPPacketReceivedCallback callback)
+{
+    g_packetReceivedCallback = callback;
 }
 
 void CAIPSetExceptionCallback(CAIPExceptionCallback callback)
 {
-OIC_LOG(DEBUG, TAG, "IN");
-
     g_exceptionCallback = callback;
+}
 
-    OIC_LOG(DEBUG, TAG, "OUT");
+void CAIPSetConnectionStateChangeCallback(CAIPConnectionStateChangeCallback callback)
+{
+    CAIPSetNetworkMonitorCallback(callback);
 }
 
 static void sendData(int fd, const CAEndpoint_t *endpoint,
@@ -689,21 +868,33 @@ static void sendData(int fd, const CAEndpoint_t *endpoint,
 {
     OIC_LOG(DEBUG, TAG, "IN");
 
+    if (!endpoint)
+    {
+        OIC_LOG(DEBUG, TAG, "endpoint is null");
+        return;
+    }
+
     char *secure = (endpoint->flags & CA_SECURE) ? "secure " : "";
     (void)secure;   // eliminates release warning
     struct sockaddr_storage sock;
     CAConvertNameToAddr(endpoint->addr, endpoint->port, &sock);
 
+    socklen_t socklen;
     if (sock.ss_family == AF_INET6)
     {
         struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sock;
         if (!sock6->sin6_scope_id)
         {
-            sock6->sin6_scope_id = endpoint->interface;
+            sock6->sin6_scope_id = endpoint->ifindex;
         }
+        socklen = sizeof(struct sockaddr_in6);
+    }
+    else
+    {
+        socklen = sizeof(struct sockaddr_in);
     }
 
-    ssize_t len = sendto(fd, data, dlen, 0, (struct sockaddr *)&sock, sizeof (sock));
+    ssize_t len = sendto(fd, data, dlen, 0, (struct sockaddr *)&sock, socklen);
     if (-1 == len)
     {
          // If logging is not defined/enabled.
@@ -713,7 +904,7 @@ static void sendData(int fd, const CAEndpoint_t *endpoint,
     }
     else
     {
-        OIC_LOG_V(INFO, TAG, "%s%s %s sendTo is successful: %d bytes", secure, cast, fam, len);
+        OIC_LOG_V(INFO, TAG, "%s%s %s sendTo is successful: %zd bytes", secure, cast, fam, len);
     }
 }
 
@@ -721,6 +912,12 @@ static void sendMulticastData6(const u_arraylist_t *iflist,
                                CAEndpoint_t *endpoint,
                                const void *data, uint32_t datalen)
 {
+    if (!endpoint)
+    {
+        OIC_LOG(DEBUG, TAG, "endpoint is null");
+        return;
+    }
+
     int scope = endpoint->flags & CA_SCOPE_MASK;
     char *ipv6mcname = ipv6mcnames[scope];
     if (!ipv6mcname)
@@ -762,7 +959,10 @@ static void sendMulticastData4(const u_arraylist_t *iflist,
                                CAEndpoint_t *endpoint,
                                const void *data, uint32_t datalen)
 {
-    struct ip_mreq mreq = { .imr_multiaddr = IPv4MulticastAddress };
+    VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
+
+    struct ip_mreqn mreq = { .imr_multiaddr = IPv4MulticastAddress,
+                             .imr_ifindex = 0 };
     OICStrcpy(endpoint->addr, sizeof(endpoint->addr), IPv4_MULTICAST);
     int fd = caglobals.ip.u4.fd;
 
@@ -785,7 +985,7 @@ static void sendMulticastData4(const u_arraylist_t *iflist,
 
         struct in_addr inaddr;
         inaddr.s_addr = ifitem->ipv4addr;
-        mreq.imr_interface = inaddr;
+        mreq.imr_address = inaddr;
         if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, &mreq, sizeof (mreq)))
         {
             OIC_LOG_V(ERROR, TAG, "send IP_MULTICAST_IF failed: %s (using defualt)",
@@ -796,7 +996,7 @@ static void sendMulticastData4(const u_arraylist_t *iflist,
 }
 
 void CAIPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
-                                                            bool isMulticast)
+                  bool isMulticast)
 {
     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
@@ -836,17 +1036,17 @@ void CAIPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
         if (caglobals.ip.ipv6enabled && (endpoint->flags & CA_IPV6))
         {
             fd = isSecure ? caglobals.ip.u6s.fd : caglobals.ip.u6.fd;
-            #ifndef __WITH_DTLS__
+#ifndef __WITH_DTLS__
             fd = caglobals.ip.u6.fd;
-            #endif
+#endif
             sendData(fd, endpoint, data, datalen, "unicast", "ipv6");
         }
         if (caglobals.ip.ipv4enabled && (endpoint->flags & CA_IPV4))
         {
             fd = isSecure ? caglobals.ip.u4s.fd : caglobals.ip.u4.fd;
-            #ifndef __WITH_DTLS__
+#ifndef __WITH_DTLS__
             fd = caglobals.ip.u4.fd;
-            #endif
+#endif
             sendData(fd, endpoint, data, datalen, "unicast", "ipv4");
         }
     }
@@ -854,8 +1054,6 @@ void CAIPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
 
 CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
 {
-    OIC_LOG(DEBUG, TAG, "IN");
-
     VERIFY_NON_NULL(info, TAG, "info is NULL");
     VERIFY_NON_NULL(size, TAG, "size is NULL");
 
@@ -867,8 +1065,14 @@ CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
     }
 
     uint32_t len = u_arraylist_length(iflist);
+    uint32_t length = len;
 
-    CAEndpoint_t *eps = (CAEndpoint_t *)OICCalloc(len, sizeof (CAEndpoint_t));
+#ifdef __WITH_DTLS__
+    //If DTLS is supported, each interface can support secure port as well
+    length = len * 2;
+#endif
+
+    CAEndpoint_t *eps = (CAEndpoint_t *)OICCalloc(length, sizeof (CAEndpoint_t));
     if (!eps)
     {
         OIC_LOG(ERROR, TAG, "Malloc Failed");
@@ -884,11 +1088,40 @@ CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
             continue;
         }
 
-        OICStrcpy(eps[j].addr, CA_INTERFACE_NAME_SIZE, ifitem->name);
-        eps[j].flags = ifitem->family == AF_INET6 ? CA_IPV6 : CA_IPV4;
         eps[j].adapter = CA_ADAPTER_IP;
-        eps[j].interface = 0;
-        eps[j].port = 0;
+        eps[j].ifindex = 0;
+
+        if (ifitem->family == AF_INET6)
+        {
+            eps[j].flags = CA_IPV6;
+            eps[j].port = caglobals.ip.u6.port;
+        }
+        else
+        {
+            eps[j].flags = CA_IPV4;
+            eps[j].port = caglobals.ip.u4.port;
+
+            inet_ntop(AF_INET, &(ifitem->ipv4addr), eps[j].addr, MAX_ADDR_STR_SIZE_CA);
+        }
+
+#ifdef __WITH_DTLS__
+        j++;
+
+        eps[j].adapter = CA_ADAPTER_IP;
+        eps[j].ifindex = 0;
+
+        if (ifitem->family == AF_INET6)
+        {
+            eps[j].flags = CA_IPV6 | CA_SECURE;
+            eps[j].port = caglobals.ip.u6s.port;
+        }
+        else
+        {
+            eps[j].flags = CA_IPV4 | CA_SECURE;
+            eps[j].port = caglobals.ip.u4s.port;
+            inet_ntop(AF_INET, &(ifitem->ipv4addr), eps[j].addr, MAX_ADDR_STR_SIZE_CA);
+        }
+#endif
         j++;
     }
 
@@ -897,7 +1130,5 @@ CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
 
     u_arraylist_destroy(iflist);
 
-    OIC_LOG(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
 }
-