[IOT-1346] Enable network status monitoring for tcp network
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / ip_adapter / caipserver.c
1 /* ****************************************************************
2  *
3  * Copyright 2014 Samsung Electronics All Rights Reserved.
4  *
5  *
6  *
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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.
18  *
19  ******************************************************************/
20
21 #ifndef __APPLE_USE_RFC_3542
22 #define __APPLE_USE_RFC_3542 // for PKTINFO
23 #endif
24 #ifndef _GNU_SOURCE
25 #define _GNU_SOURCE // for in6_pktinfo
26 #endif
27
28 #include "iotivity_config.h"
29 #include <sys/types.h>
30 #if !defined(_WIN32)
31 #include <sys/socket.h>
32 #endif
33
34 #if defined(_WIN32)
35 #include <assert.h>
36 #include <winsock2.h>
37 #include <ws2def.h>
38 #include <mswsock.h>
39 #include <ws2tcpip.h>
40 #endif
41
42 #include <stdio.h>
43 #if !defined(_MSC_VER)
44 #include <unistd.h>
45 #endif //!defined(_MSC_VER)
46 #include <sys/types.h>
47 #include <fcntl.h>
48 #if !defined(_WIN32)
49 #include <sys/select.h>
50 #include <arpa/inet.h>
51 #include <netinet/in.h>
52 #include <net/if.h>
53 #endif
54 #include <errno.h>
55 #ifdef __linux__
56 #include <linux/netlink.h>
57 #include <linux/rtnetlink.h>
58 #endif
59
60 #include <coap/pdu.h>
61 #include "caipinterface.h"
62 #include "caipnwmonitor.h"
63 #include "caadapterutils.h"
64 #ifdef __WITH_DTLS__
65 #include "caadapternetdtls.h"
66 #endif
67 #include "octhread.h"
68 #include "oic_malloc.h"
69 #include "oic_string.h"
70
71 #define USE_IP_MREQN
72 #if defined(_WIN32)
73 #undef USE_IP_MREQN
74 #endif
75
76 /*
77  * Logging tag for module name
78  */
79 #define TAG "OIC_CA_IP_SERVER"
80
81 #define SELECT_TIMEOUT 1     // select() seconds (and termination latency)
82
83 #define IPv4_MULTICAST     "224.0.1.187"
84 static struct in_addr IPv4MulticastAddress = { 0 };
85
86 #define IPv6_DOMAINS       16
87 #define IPv6_MULTICAST_INT "ff01::158"
88 static struct in6_addr IPv6MulticastAddressInt;
89 #define IPv6_MULTICAST_LNK "ff02::158"
90 static struct in6_addr IPv6MulticastAddressLnk;
91 #define IPv6_MULTICAST_RLM "ff03::158"
92 static struct in6_addr IPv6MulticastAddressRlm;
93 #define IPv6_MULTICAST_ADM "ff04::158"
94 static struct in6_addr IPv6MulticastAddressAdm;
95 #define IPv6_MULTICAST_SIT "ff05::158"
96 static struct in6_addr IPv6MulticastAddressSit;
97 #define IPv6_MULTICAST_ORG "ff08::158"
98 static struct in6_addr IPv6MulticastAddressOrg;
99 #define IPv6_MULTICAST_GLB "ff0e::158"
100 static struct in6_addr IPv6MulticastAddressGlb;
101
102 static char *ipv6mcnames[IPv6_DOMAINS] = {
103     NULL,
104     IPv6_MULTICAST_INT,
105     IPv6_MULTICAST_LNK,
106     IPv6_MULTICAST_RLM,
107     IPv6_MULTICAST_ADM,
108     IPv6_MULTICAST_SIT,
109     NULL,
110     NULL,
111     IPv6_MULTICAST_ORG,
112     NULL,
113     NULL,
114     NULL,
115     NULL,
116     NULL,
117     IPv6_MULTICAST_GLB,
118     NULL
119 };
120
121 #if defined (_WIN32)
122 #define IFF_UP_RUNNING_FLAGS  (IFF_UP)
123
124     char* caips_get_error(){
125         static char buffer[32];
126         snprintf(buffer, 32, "%i", WSAGetLastError());
127         return buffer;
128     }
129 #define CAIPS_GET_ERROR \
130     caips_get_error()
131 #else
132 #define IFF_UP_RUNNING_FLAGS  (IFF_UP|IFF_RUNNING)
133
134 #define CAIPS_GET_ERROR \
135     strerror(errno)
136 #endif
137 static CAIPErrorHandleCallback g_ipErrorHandler = NULL;
138
139 static CAIPPacketReceivedCallback g_packetReceivedCallback = NULL;
140
141 static void CAFindReadyMessage();
142 #if !defined(WSA_WAIT_EVENT_0)
143 static void CASelectReturned(fd_set *readFds, int ret);
144 #else
145 static void CAEventReturned(CASocketFd_t socket);
146 #endif
147 static void CAProcessNewInterface(CAInterface_t *ifchanged);
148 static CAResult_t CAReceiveMessage(CASocketFd_t fd, CATransportFlags_t flags);
149
150 static void CAReceiveHandler(void *data)
151 {
152     (void)data;
153
154     while (!caglobals.ip.terminate)
155     {
156         CAFindReadyMessage();
157     }
158 }
159
160 #if !defined(WSA_WAIT_EVENT_0)
161
162 #define CLOSE_SOCKET(TYPE) \
163     if (caglobals.ip.TYPE.fd != OC_INVALID_SOCKET) \
164     { \
165         close(caglobals.ip.TYPE.fd); \
166         caglobals.ip.TYPE.fd = OC_INVALID_SOCKET; \
167     }
168
169 #define SET(TYPE, FDS) \
170     if (caglobals.ip.TYPE.fd != OC_INVALID_SOCKET) \
171     { \
172         FD_SET(caglobals.ip.TYPE.fd, FDS); \
173     }
174
175 #define ISSET(TYPE, FDS, FLAGS) \
176     if (caglobals.ip.TYPE.fd != OC_INVALID_SOCKET && FD_ISSET(caglobals.ip.TYPE.fd, FDS)) \
177     { \
178         fd = caglobals.ip.TYPE.fd; \
179         flags = FLAGS; \
180     }
181
182
183 static void CAFindReadyMessage()
184 {
185     fd_set readFds;
186     struct timeval timeout;
187
188     timeout.tv_sec = caglobals.ip.selectTimeout;
189     timeout.tv_usec = 0;
190     struct timeval *tv = caglobals.ip.selectTimeout == -1 ? NULL : &timeout;
191
192     FD_ZERO(&readFds);
193     SET(u6,  &readFds)
194     SET(u6s, &readFds)
195     SET(u4,  &readFds)
196     SET(u4s, &readFds)
197     SET(m6,  &readFds)
198     SET(m6s, &readFds)
199     SET(m4,  &readFds)
200     SET(m4s, &readFds)
201
202     if (caglobals.ip.shutdownFds[0] != -1)
203     {
204         FD_SET(caglobals.ip.shutdownFds[0], &readFds);
205     }
206     if (caglobals.ip.netlinkFd != OC_INVALID_SOCKET)
207     {
208         FD_SET(caglobals.ip.netlinkFd, &readFds);
209     }
210
211     int ret = select(caglobals.ip.maxfd + 1, &readFds, NULL, NULL, tv);
212
213     if (caglobals.ip.terminate)
214     {
215         OIC_LOG_V(DEBUG, TAG, "Packet receiver Stop request received.");
216         return;
217     }
218
219     if (ret <= 0)
220     {
221         if (ret < 0)
222         {
223             OIC_LOG_V(FATAL, TAG, "select error %s", CAIPS_GET_ERROR);
224         }
225         return;
226     }
227
228     CASelectReturned(&readFds, ret);
229 }
230
231 static void CASelectReturned(fd_set *readFds, int ret)
232 {
233     (void)ret;
234     CASocketFd_t fd = OC_INVALID_SOCKET;
235     CATransportFlags_t flags = CA_DEFAULT_FLAGS;
236
237     while (!caglobals.ip.terminate)
238     {
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 != OC_INVALID_SOCKET) && FD_ISSET(caglobals.ip.netlinkFd, readFds))
248         {
249             CAInterface_t *ifchanged = CAFindInterfaceChange();
250             if (ifchanged)
251             {
252                 CAProcessNewInterface(ifchanged);
253                 OICFree(ifchanged);
254             }
255             break;
256         }
257         else if (FD_ISSET(caglobals.ip.shutdownFds[0], readFds))
258         {
259             char buf[10] = {0};
260             ssize_t len = read(caglobals.ip.shutdownFds[0], buf, sizeof (buf));
261             if (-1 == len)
262             {
263                 continue;
264             }
265             break;
266         }
267         else
268         {
269             break;
270         }
271         (void)CAReceiveMessage(fd, flags);
272         FD_CLR(fd, readFds);
273     }
274 }
275
276 #else // if defined(WSA_WAIT_EVENT_0)
277
278 #define CLOSE_SOCKET(TYPE) \
279     if (caglobals.ip.TYPE.fd != OC_INVALID_SOCKET) \
280     { \
281         closesocket(caglobals.ip.TYPE.fd); \
282         caglobals.ip.TYPE.fd = OC_INVALID_SOCKET; \
283     }
284
285 #define PUSH_HANDLE(HANDLE, ARRAY, INDEX) \
286 { \
287     ARRAY[INDEX] = HANDLE; \
288     INDEX++; \
289 }
290
291 // Turn handle into WSAEvent and push to ARRAY
292 #define PUSH_SOCKET(SOCKET, ARRAY, INDEX) \
293     if (SOCKET != OC_INVALID_SOCKET) \
294     { \
295         WSAEVENT NewEvent; \
296         NewEvent = WSACreateEvent(); \
297         if (WSA_INVALID_EVENT != NewEvent) \
298         { \
299             if (0 != WSAEventSelect(SOCKET, NewEvent, FD_READ)) \
300             { \
301                 OIC_LOG_V(ERROR, TAG, "WSAEventSelect failed 0x%08x ", WSAGetLastError()); \
302                 if (!WSACloseEvent(NewEvent)) \
303                 { \
304                     OIC_LOG_V(ERROR, TAG, "WSACloseEvent(NewEvent) failed 0x%08x", WSAGetLastError()); \
305                 } \
306             } \
307             else \
308             { \
309                 PUSH_HANDLE(NewEvent, ARRAY, INDEX); \
310             } \
311         } \
312         else \
313         { \
314             OIC_LOG_V(ERROR, TAG, "WSACreateEvent(NewEvent) failed 0x%08x", WSAGetLastError()); \
315         }\
316     }
317
318 #define INSERT_SOCKET(FD, ARRAY, INDEX) \
319     { \
320         if (OC_INVALID_SOCKET != FD) \
321         { \
322             ARRAY[INDEX] = FD; \
323         } \
324     }
325
326
327 // Inserts the socket into the SOCKET_ARRAY and pushes the socket event into EVENT_ARRAY
328 #define PUSH_IP_SOCKET(TYPE, EVENT_ARRAY, SOCKET_ARRAY, INDEX) \
329     { \
330         if (OC_INVALID_SOCKET != caglobals.ip.TYPE.fd) \
331         { \
332             INSERT_SOCKET(caglobals.ip.TYPE.fd, SOCKET_ARRAY, INDEX); \
333             PUSH_SOCKET(caglobals.ip.TYPE.fd, EVENT_ARRAY, INDEX); \
334         } \
335     }
336
337 #define IS_MATCHING_IP_SOCKET(TYPE, SOCKET, FLAGS) \
338     if ((caglobals.ip.TYPE.fd != OC_INVALID_SOCKET) && (caglobals.ip.TYPE.fd == SOCKET)) \
339     { \
340         fd = caglobals.ip.TYPE.fd; \
341         flags = FLAGS; \
342     }
343
344 #define EVENT_ARRAY_SIZE  10
345
346 static void CAFindReadyMessage()
347 {
348     CASocketFd_t socketArray[EVENT_ARRAY_SIZE];
349     HANDLE eventArray[EVENT_ARRAY_SIZE];
350     int arraySize = 0;
351     int eventIndex;
352
353     // socketArray and eventArray should have same number of elements
354     OC_STATIC_ASSERT(_countof(socketArray) == _countof(eventArray), "Arrays should have same number of elements");
355
356     PUSH_IP_SOCKET(u6,  eventArray, socketArray, arraySize);
357     PUSH_IP_SOCKET(u6s, eventArray, socketArray, arraySize);
358     PUSH_IP_SOCKET(u4,  eventArray, socketArray, arraySize);
359     PUSH_IP_SOCKET(u4s, eventArray, socketArray, arraySize);
360     PUSH_IP_SOCKET(m6,  eventArray, socketArray, arraySize);
361     PUSH_IP_SOCKET(m6s, eventArray, socketArray, arraySize);
362     PUSH_IP_SOCKET(m4,  eventArray, socketArray, arraySize);
363     PUSH_IP_SOCKET(m4s, eventArray, socketArray, arraySize);
364
365     if (WSA_INVALID_EVENT != caglobals.ip.shutdownEvent)
366     {
367         INSERT_SOCKET(OC_INVALID_SOCKET, socketArray, arraySize);
368         PUSH_HANDLE(caglobals.ip.shutdownEvent, eventArray, arraySize);
369     }
370
371     /** @todo Support netlink events */
372
373     // Should not have overflowed buffer
374     assert(arraySize <= (_countof(socketArray)));
375
376     // Timeout is unnecessary on Windows
377     assert(-1 == caglobals.ip.selectTimeout);
378
379     while (!caglobals.ip.terminate)
380     {
381         int ret = WSAWaitForMultipleEvents(arraySize, eventArray, FALSE, WSA_INFINITE, FALSE);
382
383         switch (ret)
384         {
385             case WSA_WAIT_FAILED:
386                 OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents returned WSA_WAIT_FAILED 0x%08x", WSAGetLastError());
387                 break;
388             case WSA_WAIT_IO_COMPLETION:
389                 OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents returned WSA_WAIT_IO_COMPLETION 0x%08x", WSAGetLastError());
390                 break;
391             case WSA_WAIT_TIMEOUT:
392                 OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents returned WSA_WAIT_TIMEOUT 0x%08x", WSAGetLastError());
393                 break;
394             default:
395                 eventIndex = ret - WSA_WAIT_EVENT_0;
396                 if ((eventIndex >= 0) && (eventIndex < arraySize))
397                 {
398                     if (false == WSAResetEvent(eventArray[eventIndex]))
399                     {
400                         OIC_LOG_V(ERROR, TAG, "WSAResetEvent failed 0x%08x", WSAGetLastError());
401                     }
402
403                     // Break out if shutdownEvent is triggered
404                     if ((caglobals.ip.shutdownEvent != WSA_INVALID_EVENT) &&
405                         (caglobals.ip.shutdownEvent == eventArray[eventIndex]))
406                     {
407                         break;
408                     }
409                     CAEventReturned(socketArray[eventIndex]);
410                 }
411                 else
412                 {
413                     OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents failed 0x%08x", WSAGetLastError());
414                 }
415                 break;
416         }
417
418     }
419
420     while (arraySize > 0)
421     {
422         arraySize--;
423         if (!WSACloseEvent(eventArray[arraySize]))
424         {
425             OIC_LOG_V(ERROR, TAG, "WSACloseEvent (Index %i) failed 0x%08x", arraySize, WSAGetLastError());
426         }
427     }
428
429     if (caglobals.ip.terminate)
430     {
431         caglobals.ip.shutdownEvent = WSA_INVALID_EVENT;
432         WSACleanup();
433     }
434 }
435
436 static void CAEventReturned(CASocketFd_t socket)
437 {
438     CASocketFd_t fd = OC_INVALID_SOCKET;
439     CATransportFlags_t flags = CA_DEFAULT_FLAGS;
440
441     while (!caglobals.ip.terminate)
442     {
443         IS_MATCHING_IP_SOCKET(u6,  socket, CA_IPV6)
444         else IS_MATCHING_IP_SOCKET(u6s, socket, CA_IPV6 | CA_SECURE)
445         else IS_MATCHING_IP_SOCKET(u4,  socket, CA_IPV4)
446         else IS_MATCHING_IP_SOCKET(u4s, socket, CA_IPV4 | CA_SECURE)
447         else IS_MATCHING_IP_SOCKET(m6,  socket, CA_MULTICAST | CA_IPV6)
448         else IS_MATCHING_IP_SOCKET(m6s, socket, CA_MULTICAST | CA_IPV6 | CA_SECURE)
449         else IS_MATCHING_IP_SOCKET(m4,  socket, CA_MULTICAST | CA_IPV4)
450         else IS_MATCHING_IP_SOCKET(m4s, socket, CA_MULTICAST | CA_IPV4 | CA_SECURE)
451         else
452         {
453             break;
454         }
455         (void)CAReceiveMessage(socket, flags);
456         // We will never get more than one match per socket, so always break.
457         break;
458     }
459 }
460
461 #endif
462
463 void CADeInitializeIPGlobals()
464 {
465     CLOSE_SOCKET(u6);
466     CLOSE_SOCKET(u6s);
467     CLOSE_SOCKET(u4);
468     CLOSE_SOCKET(u4s);
469     CLOSE_SOCKET(m6);
470     CLOSE_SOCKET(m6s);
471     CLOSE_SOCKET(m4);
472     CLOSE_SOCKET(m4s);
473
474     if (caglobals.ip.netlinkFd != OC_INVALID_SOCKET)
475     {
476 #ifdef _WIN32
477         closesocket(caglobals.ip.netlinkFd);
478 #else
479         close(caglobals.ip.netlinkFd);
480 #endif
481         caglobals.ip.netlinkFd = OC_INVALID_SOCKET;
482     }
483 }
484
485 static CAResult_t CAReceiveMessage(CASocketFd_t fd, CATransportFlags_t flags)
486 {
487     char recvBuffer[COAP_MAX_PDU_SIZE] = {0};
488
489     size_t len = 0;
490     int level = 0;
491     int type = 0;
492     int namelen = 0;
493     struct sockaddr_storage srcAddr = { .ss_family = 0 };
494     unsigned char *pktinfo = NULL;
495 #if !defined(WSA_CMSG_DATA)
496     struct cmsghdr *cmp = NULL;
497     struct iovec iov = { .iov_base = recvBuffer, .iov_len = sizeof (recvBuffer) };
498     union control
499     {
500         struct cmsghdr cmsg;
501         unsigned char data[CMSG_SPACE(sizeof (struct in6_pktinfo))];
502     } cmsg;
503
504     if (flags & CA_IPV6)
505     {
506         namelen = sizeof (struct sockaddr_in6);
507         level = IPPROTO_IPV6;
508         type = IPV6_PKTINFO;
509         len = sizeof (struct in6_pktinfo);
510     }
511     else
512     {
513         namelen = sizeof (struct sockaddr_in);
514         level = IPPROTO_IP;
515         type = IP_PKTINFO;
516         len = sizeof (struct in6_pktinfo);
517     }
518
519     struct msghdr msg = { .msg_name = &srcAddr,
520                           .msg_namelen = namelen,
521                           .msg_iov = &iov,
522                           .msg_iovlen = 1,
523                           .msg_control = &cmsg,
524                           .msg_controllen = CMSG_SPACE(len) };
525
526     ssize_t recvLen = recvmsg(fd, &msg, flags);
527     if (OC_SOCKET_ERROR == recvLen)
528     {
529         OIC_LOG_V(ERROR, TAG, "Recvfrom failed %s", strerror(errno));
530         return CA_STATUS_FAILED;
531     }
532
533     if (flags & CA_MULTICAST)
534     {
535         for (cmp = CMSG_FIRSTHDR(&msg); cmp != NULL; cmp = CMSG_NXTHDR(&msg, cmp))
536         {
537             if (cmp->cmsg_level == level && cmp->cmsg_type == type)
538             {
539                 pktinfo = CMSG_DATA(cmp);
540             }
541         }
542     }
543 #else // if defined(WSA_CMSG_DATA)
544     union control
545     {
546         WSACMSGHDR cmsg;
547         uint8_t data[WSA_CMSG_SPACE(sizeof (IN6_PKTINFO))];
548     } cmsg;
549     memset(&cmsg, 0, sizeof(cmsg));
550
551     if (flags & CA_IPV6)
552     {
553         namelen  = sizeof (struct sockaddr_in6);
554         level = IPPROTO_IPV6;
555         type = IPV6_PKTINFO;
556     }
557     else
558     {
559         namelen = sizeof (struct sockaddr_in);
560         level = IPPROTO_IP;
561         type = IP_PKTINFO;
562     }
563
564     WSABUF iov = {.len = sizeof (recvBuffer), .buf = recvBuffer};
565     WSAMSG msg = {.name = (PSOCKADDR)&srcAddr,
566                   .namelen = namelen,
567                   .lpBuffers = &iov,
568                   .dwBufferCount = 1,
569                   .Control = {.buf = cmsg.data, .len = sizeof (cmsg)}
570                  };
571
572     uint32_t recvLen = 0;
573     uint32_t ret = caglobals.ip.wsaRecvMsg(fd, &msg, &recvLen, 0,0);
574     OIC_LOG_V(DEBUG, TAG, "WSARecvMsg recvd %u bytes", recvLen);
575     if (OC_SOCKET_ERROR == ret)
576     {
577         OIC_LOG_V(ERROR, TAG, "WSARecvMsg failed %i", WSAGetLastError());
578     }
579
580     if (flags & CA_MULTICAST)
581     {
582         for (WSACMSGHDR *cmp = WSA_CMSG_FIRSTHDR(&msg); cmp != NULL;
583              cmp = WSA_CMSG_NXTHDR(&msg, cmp))
584         {
585             if (cmp->cmsg_level == level && cmp->cmsg_type == type)
586             {
587                 pktinfo = WSA_CMSG_DATA(cmp);
588             }
589         }
590     }
591 #endif // !defined(WSA_CMSG_DATA)
592     CASecureEndpoint_t sep = {.endpoint = {.adapter = CA_ADAPTER_IP, .flags = flags}};
593
594     if (flags & CA_IPV6)
595     {
596         /** @todo figure out correct usage for ifindex, and sin6_scope_id.*/
597         if ((flags & CA_MULTICAST) && pktinfo)
598         {
599             struct in6_addr *addr = &(((struct in6_pktinfo *)pktinfo)->ipi6_addr);
600             unsigned char topbits = ((unsigned char *)addr)[0];
601             if (topbits != 0xff)
602             {
603                 sep.endpoint.flags &= ~CA_MULTICAST;
604             }
605         }
606     }
607     else
608     {
609         if ((flags & CA_MULTICAST) && pktinfo)
610         {
611             struct in_addr *addr = &((struct in_pktinfo *)pktinfo)->ipi_addr;
612             uint32_t host = ntohl(addr->s_addr);
613             unsigned char topbits = ((unsigned char *)&host)[3];
614             if (topbits < 224 || topbits > 239)
615             {
616                 sep.endpoint.flags &= ~CA_MULTICAST;
617             }
618         }
619     }
620
621     CAConvertAddrToName(&srcAddr, namelen, sep.endpoint.addr, &sep.endpoint.port);
622
623     if (flags & CA_SECURE)
624     {
625 #ifdef __WITH_DTLS__
626         int ret = CAAdapterNetDtlsDecrypt(&sep, (uint8_t *)recvBuffer, recvLen);
627         OIC_LOG_V(DEBUG, TAG, "CAAdapterNetDtlsDecrypt returns [%d]", ret);
628 #else
629         OIC_LOG(ERROR, TAG, "Encrypted message but no DTLS");
630 #endif
631     }
632     else
633     {
634         if (g_packetReceivedCallback)
635         {
636             g_packetReceivedCallback(&sep, recvBuffer, recvLen);
637         }
638     }
639
640     return CA_STATUS_OK;
641
642 }
643
644 void CAIPPullData()
645 {
646     OIC_LOG(DEBUG, TAG, "IN");
647     OIC_LOG(DEBUG, TAG, "OUT");
648 }
649
650 static CASocketFd_t CACreateSocket(int family, uint16_t *port, bool isMulticast)
651 {
652     int socktype = SOCK_DGRAM;
653 #ifdef SOCK_CLOEXEC
654     socktype |= SOCK_CLOEXEC;
655 #endif
656     CASocketFd_t fd = socket(family, socktype, IPPROTO_UDP);
657     if (OC_INVALID_SOCKET == fd)
658     {
659         OIC_LOG_V(ERROR, TAG, "create socket failed: %s", CAIPS_GET_ERROR);
660         return OC_INVALID_SOCKET;
661     }
662
663 #if !defined(SOCK_CLOEXEC) && defined(FD_CLOEXEC)
664     int fl = fcntl(fd, F_GETFD);
665     if (-1 == fl || -1 == fcntl(fd, F_SETFD, fl|FD_CLOEXEC))
666     {
667         OIC_LOG_V(ERROR, TAG, "set FD_CLOEXEC failed: %s", strerror(errno));
668         close(fd);
669         return OC_INVALID_SOCKET;
670     }
671 #endif
672     struct sockaddr_storage sa = { .ss_family = family };
673     socklen_t socklen = 0;
674
675     if (family == AF_INET6)
676     {
677         int on = 1;
678
679         if (OC_SOCKET_ERROR == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, OPTVAL_T(&on), sizeof (on)))
680         {
681             OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", CAIPS_GET_ERROR);
682         }
683
684         if (isMulticast && *port) // only do this for multicast ports
685         {
686 #if defined(IPV6_RECVPKTINFO)
687             if (OC_SOCKET_ERROR == setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof (on)))
688 #else
689             if (OC_SOCKET_ERROR == setsockopt(fd, IPPROTO_IPV6, IPV6_PKTINFO, OPTVAL_T(&on), sizeof (on)))
690 #endif
691             {
692                 OIC_LOG_V(ERROR, TAG, "IPV6_RECVPKTINFO failed: %s",CAIPS_GET_ERROR);
693             }
694         }
695
696         ((struct sockaddr_in6 *)&sa)->sin6_port = htons(*port);
697         socklen = sizeof (struct sockaddr_in6);
698     }
699     else
700     {
701         if (isMulticast && *port) // only do this for multicast ports
702         {
703             int on = 1;
704             if (OC_SOCKET_ERROR == setsockopt(fd, IPPROTO_IP, IP_PKTINFO, OPTVAL_T(&on), sizeof (on)))
705             {
706                 OIC_LOG_V(ERROR, TAG, "IP_PKTINFO failed: %s", CAIPS_GET_ERROR);
707             }
708         }
709
710         ((struct sockaddr_in *)&sa)->sin_port = htons(*port);
711         socklen = sizeof (struct sockaddr_in);
712     }
713
714     if (isMulticast && *port) // use the given port
715     {
716         int on = 1;
717         if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof (on)))
718         {
719             OIC_LOG_V(ERROR, TAG, "SO_REUSEADDR failed: %s", CAIPS_GET_ERROR);
720 #ifdef _WIN32
721             closesocket(fd);
722 #else
723             close(fd);
724 #endif
725             return OC_INVALID_SOCKET;
726         }
727     }
728
729     if (OC_SOCKET_ERROR == bind(fd, (struct sockaddr *)&sa, socklen))
730     {
731         OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", CAIPS_GET_ERROR);
732 #ifdef _WIN32
733         closesocket(fd);
734 #else
735         close(fd);
736 #endif
737         return OC_INVALID_SOCKET;
738     }
739
740     if (!*port) // return the assigned port
741     {
742         if (OC_SOCKET_ERROR == getsockname(fd, (struct sockaddr *)&sa, &socklen))
743         {
744             OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", CAIPS_GET_ERROR);
745 #ifdef _WIN32
746             closesocket(fd);
747 #else
748             close(fd);
749 #endif
750             return OC_INVALID_SOCKET;
751         }
752         *port = ntohs(family == AF_INET6 ?
753                       ((struct sockaddr_in6 *)&sa)->sin6_port :
754                       ((struct sockaddr_in *)&sa)->sin_port);
755     }
756
757     return fd;
758 }
759
760 #define CHECKFD(FD) \
761     if (FD > caglobals.ip.maxfd) \
762         caglobals.ip.maxfd = FD;
763 #define NEWSOCKET(FAMILY, NAME, MULTICAST) \
764     caglobals.ip.NAME.fd = CACreateSocket(FAMILY, &caglobals.ip.NAME.port, MULTICAST); \
765     if (caglobals.ip.NAME.fd == OC_INVALID_SOCKET) \
766     {   \
767         caglobals.ip.NAME.port = 0; \
768         caglobals.ip.NAME.fd = CACreateSocket(FAMILY, &caglobals.ip.NAME.port, MULTICAST); \
769     }   \
770     CHECKFD(caglobals.ip.NAME.fd)
771
772 static void CAInitializeNetlink()
773 {
774     caglobals.ip.netlinkFd = OC_INVALID_SOCKET;
775 #ifdef __linux__
776     // create NETLINK fd for interface change notifications
777     struct sockaddr_nl sa = { AF_NETLINK, 0, 0, RTMGRP_LINK };
778
779     caglobals.ip.netlinkFd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC, NETLINK_ROUTE);
780     if (caglobals.ip.netlinkFd == OC_INVALID_SOCKET)
781     {
782         OIC_LOG_V(ERROR, TAG, "netlink socket failed: %s", strerror(errno));
783     }
784     else
785     {
786         int r = bind(caglobals.ip.netlinkFd, (struct sockaddr *)&sa, sizeof (sa));
787         if (r)
788         {
789             OIC_LOG_V(ERROR, TAG, "netlink bind failed: %s", strerror(errno));
790             close(caglobals.ip.netlinkFd);
791             caglobals.ip.netlinkFd = OC_INVALID_SOCKET;
792         }
793         else
794         {
795             CHECKFD(caglobals.ip.netlinkFd);
796         }
797     }
798 #endif
799 }
800
801 static void CAInitializeFastShutdownMechanism()
802 {
803     caglobals.ip.selectTimeout = -1; // don't poll for shutdown
804     int ret = -1;
805 #if defined(WSA_WAIT_EVENT_0)
806     caglobals.ip.shutdownEvent = WSACreateEvent();
807     if (WSA_INVALID_EVENT != caglobals.ip.shutdownEvent)
808     {
809         ret = 0;
810     }
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]);
815 #else
816     ret = pipe(caglobals.ip.shutdownFds);
817     if (-1 != ret)
818     {
819         ret = fcntl(caglobals.ip.shutdownFds[0], F_GETFD);
820         if (-1 != ret)
821         {
822             ret = fcntl(caglobals.ip.shutdownFds[0], F_SETFD, ret|FD_CLOEXEC);
823         }
824         if (-1 != ret)
825         {
826             ret = fcntl(caglobals.ip.shutdownFds[1], F_GETFD);
827         }
828         if (-1 != ret)
829         {
830             ret = fcntl(caglobals.ip.shutdownFds[1], F_SETFD, ret|FD_CLOEXEC);
831         }
832         if (-1 == ret)
833         {
834             close(caglobals.ip.shutdownFds[1]);
835             close(caglobals.ip.shutdownFds[0]);
836             caglobals.ip.shutdownFds[0] = -1;
837             caglobals.ip.shutdownFds[1] = -1;
838         }
839     }
840     CHECKFD(caglobals.ip.shutdownFds[0]);
841     CHECKFD(caglobals.ip.shutdownFds[1]);
842 #endif
843     if (-1 == ret)
844     {
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
847     }
848 }
849
850 CAResult_t CAIPStartServer(const ca_thread_pool_t threadPool)
851 {
852     CAResult_t res = CA_STATUS_OK;
853
854     if (caglobals.ip.started)
855     {
856         return res;
857     }
858 #if defined (_WIN32)
859     WORD wVersionRequested = MAKEWORD(2, 2);
860     WSADATA wsaData ={.wVersion = 0};
861     int err = WSAStartup(wVersionRequested, &wsaData);
862     if (err != 0)
863     {
864         OIC_LOG_V(ERROR, TAG, "WSAStartup failed: %i", err);
865         return CA_STATUS_FAILED;
866     }
867     OIC_LOG(DEBUG, TAG, "WSAStartup Succeeded");
868 #endif
869     if (!IPv4MulticastAddress.s_addr)
870     {
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);
879     }
880
881     if (!caglobals.ip.ipv6enabled && !caglobals.ip.ipv4enabled)
882     {
883         caglobals.ip.ipv4enabled = true;  // only needed to run CA tests
884     }
885
886     if (caglobals.ip.ipv6enabled)
887     {
888         NEWSOCKET(AF_INET6, u6, false)
889         NEWSOCKET(AF_INET6, u6s, false)
890         NEWSOCKET(AF_INET6, m6, true)
891         NEWSOCKET(AF_INET6, m6s, true)
892         OIC_LOG_V(INFO, TAG, "IPv6 unicast port: %u", caglobals.ip.u6.port);
893     }
894     if (caglobals.ip.ipv4enabled)
895     {
896         NEWSOCKET(AF_INET, u4, false)
897         NEWSOCKET(AF_INET, u4s, false)
898         NEWSOCKET(AF_INET, m4, true)
899         NEWSOCKET(AF_INET, m4s, true)
900         OIC_LOG_V(INFO, TAG, "IPv4 unicast port: %u", caglobals.ip.u4.port);
901     }
902
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);
907
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;
917     DWORD copied = 0;
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);
919     if (0 != err)
920     {
921         OIC_LOG_V(ERROR, TAG, "WSAIoctl failed %i", WSAGetLastError());
922         return CA_STATUS_FAILED;
923     }
924 #endif
925     // set up appropriate FD mechanism for fast shutdown
926     CAInitializeFastShutdownMechanism();
927
928     // create source of network interface change notifications
929     CAInitializeNetlink();
930
931     caglobals.ip.selectTimeout = CAGetPollingInterval(caglobals.ip.selectTimeout);
932
933     res = CAIPStartListenServer();
934     if (CA_STATUS_OK != res)
935     {
936         OIC_LOG_V(ERROR, TAG, "Failed to start listening server![%d]", res);
937         return res;
938     }
939
940     caglobals.ip.terminate = false;
941     res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
942     if (CA_STATUS_OK != res)
943     {
944         OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
945         return res;
946     }
947     OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
948
949     caglobals.ip.started = true;
950     return CA_STATUS_OK;
951 }
952
953 void CAIPStopServer()
954 {
955     caglobals.ip.started = false;
956     caglobals.ip.terminate = true;
957
958 #if !defined(WSA_WAIT_EVENT_0)
959     if (caglobals.ip.shutdownFds[1] != -1)
960     {
961         close(caglobals.ip.shutdownFds[1]);
962         // receive thread will stop immediately
963     }
964     else
965     {
966         // receive thread will stop in SELECT_TIMEOUT seconds.
967     }
968 #else
969     // receive thread will stop immediately.
970     if (!WSASetEvent(caglobals.ip.shutdownEvent))
971     {
972         OIC_LOG_V(DEBUG, TAG, "set shutdown event failed: %#08X", GetLastError());
973     }
974 #endif
975 }
976
977 void CAWakeUpForChange()
978 {
979 #if !defined(WSA_WAIT_EVENT_0)
980     if (caglobals.ip.shutdownFds[1] != -1)
981     {
982         ssize_t len = 0;
983         do
984         {
985             len = write(caglobals.ip.shutdownFds[1], "w", 1);
986         } while ((len == -1) && (errno == EINTR));
987         if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
988         {
989             OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
990         }
991     }
992 #else
993     if (!WSASetEvent(caglobals.ip.shutdownEvent))
994     {
995         OIC_LOG_V(DEBUG, TAG, "set shutdown event failed: %#08X", GetLastError());
996     }
997 #endif
998 }
999
1000 static void applyMulticastToInterface4(uint32_t ifindex)
1001 {
1002     if (!caglobals.ip.ipv4enabled)
1003     {
1004         return;
1005     }
1006
1007 #if defined(USE_IP_MREQN)
1008     struct ip_mreqn mreq = { .imr_multiaddr = IPv4MulticastAddress,
1009                              .imr_address.s_addr = htonl(INADDR_ANY),
1010                              .imr_ifindex = ifindex };
1011 #else
1012     struct ip_mreq mreq  = { .imr_multiaddr.s_addr = IPv4MulticastAddress.s_addr,
1013                              .imr_interface.s_addr = htonl(ifindex) };
1014 #endif
1015
1016     int ret = setsockopt(caglobals.ip.m4.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, OPTVAL_T(&mreq), sizeof (mreq));
1017     if (OC_SOCKET_ERROR == ret)
1018     {
1019 #if !defined(WSAEINVAL)
1020         if (EADDRINUSE != errno)
1021 #else
1022         if (WSAEINVAL != WSAGetLastError()) // Joining multicast group more than once (IPv4 Flavor)
1023 #endif
1024         {
1025             OIC_LOG_V(ERROR, TAG, "       IPv4 IP_ADD_MEMBERSHIP failed: %s", CAIPS_GET_ERROR);
1026         }
1027     }
1028     ret = setsockopt(caglobals.ip.m4s.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, OPTVAL_T(&mreq), sizeof (mreq));
1029     if (OC_SOCKET_ERROR == ret)
1030     {
1031 #if !defined(WSAEINVAL)
1032         if (EADDRINUSE != errno)
1033 #else
1034         if (WSAEINVAL != WSAGetLastError()) // Joining multicast group more than once (IPv4 Flavor)
1035 #endif
1036         {
1037             OIC_LOG_V(ERROR, TAG, "SECURE IPv4 IP_ADD_MEMBERSHIP failed: %s", CAIPS_GET_ERROR);
1038         }
1039     }
1040 }
1041
1042 static void applyMulticast6(int fd, struct in6_addr *addr, uint32_t ifindex)
1043 {
1044     struct ipv6_mreq mreq = {.ipv6mr_multiaddr = {0},
1045                              .ipv6mr_interface = ifindex };
1046
1047     // VS2013 has problems with struct copies inside struct initializers, so copy separately.
1048     mreq.ipv6mr_multiaddr = *addr;
1049
1050     int ret = setsockopt(fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, OPTVAL_T(&mreq), sizeof (mreq));
1051     if (OC_SOCKET_ERROR == ret)
1052     {
1053 #if !defined(_WIN32)
1054                 if (EADDRINUSE != errno)
1055 #else
1056                 if (WSAEINVAL != WSAGetLastError()) // Joining multicast group more than once (IPv6 Flavor)
1057 #endif
1058         {
1059             OIC_LOG_V(ERROR, TAG, "IPv6 IPV6_JOIN_GROUP failed: %s", CAIPS_GET_ERROR);
1060         }
1061     }
1062 }
1063
1064 static void applyMulticastToInterface6(uint32_t ifindex)
1065 {
1066     if (!caglobals.ip.ipv6enabled)
1067     {
1068         return;
1069     }
1070     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressInt, ifindex);
1071     applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressLnk, ifindex);
1072     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressRlm, ifindex);
1073     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressAdm, ifindex);
1074     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressSit, ifindex);
1075     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressOrg, ifindex);
1076     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressGlb, ifindex);
1077
1078     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressInt, ifindex);
1079     applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressLnk, ifindex);
1080     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressRlm, ifindex);
1081     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressAdm, ifindex);
1082     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressSit, ifindex);
1083     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressOrg, ifindex);
1084     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressGlb, ifindex);
1085 }
1086
1087 CAResult_t CAIPStartListenServer()
1088 {
1089     u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
1090     if (!iflist)
1091     {
1092         OIC_LOG_V(ERROR, TAG, "CAIPGetInterfaceInformation() failed: %s", strerror(errno));
1093         return CA_STATUS_FAILED;
1094     }
1095
1096     uint32_t len = u_arraylist_length(iflist);
1097     OIC_LOG_V(DEBUG, TAG, "IP network interfaces found: %d", len);
1098
1099     for (uint32_t i = 0; i < len; i++)
1100     {
1101         CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1102
1103         if (!ifitem)
1104         {
1105             continue;
1106         }
1107         if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
1108         {
1109             continue;
1110         }
1111         if (ifitem->family == AF_INET)
1112         {
1113             OIC_LOG_V(DEBUG, TAG, "Adding IPv4 interface %i to multicast group", ifitem->index);
1114             applyMulticastToInterface4(ifitem->index);
1115         }
1116         if (ifitem->family == AF_INET6)
1117         {
1118             OIC_LOG_V(DEBUG, TAG, "Adding IPv6 interface %i to multicast group", ifitem->index);
1119             applyMulticastToInterface6(ifitem->index);
1120         }
1121     }
1122
1123     u_arraylist_destroy(iflist);
1124     return CA_STATUS_OK;
1125 }
1126
1127 CAResult_t CAIPStopListenServer()
1128 {
1129     u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
1130     if (!iflist)
1131     {
1132         OIC_LOG_V(ERROR, TAG, "Get interface info failed: %s", strerror(errno));
1133         return CA_STATUS_FAILED;
1134     }
1135
1136     uint32_t len = u_arraylist_length(iflist);
1137     OIC_LOG_V(DEBUG, TAG, "IP network interfaces found: %d", len);
1138
1139     for (uint32_t i = 0; i < len; i++)
1140     {
1141         CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1142
1143         if (!ifitem)
1144         {
1145             continue;
1146         }
1147         if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
1148         {
1149             continue;
1150         }
1151         if (ifitem->family == AF_INET)
1152         {
1153             CLOSE_SOCKET(m4);
1154             CLOSE_SOCKET(m4s);
1155             OIC_LOG_V(DEBUG, TAG, "IPv4 network interface: %s cloed", ifitem->name);
1156         }
1157         if (ifitem->family == AF_INET6)
1158         {
1159             CLOSE_SOCKET(m6);
1160             CLOSE_SOCKET(m6s);
1161             OIC_LOG_V(DEBUG, TAG, "IPv6 network interface: %s", ifitem->name);
1162         }
1163     }
1164     u_arraylist_destroy(iflist);
1165     return CA_STATUS_OK;
1166 }
1167
1168 static void CAProcessNewInterface(CAInterface_t *ifitem)
1169 {
1170     if (!ifitem)
1171     {
1172         OIC_LOG(DEBUG, TAG, "ifitem is null");
1173         return;
1174     }
1175
1176     if (ifitem->family == AF_INET6)
1177     {
1178         applyMulticastToInterface6(ifitem->index);
1179     }
1180     if (ifitem->family == AF_INET)
1181     {
1182         applyMulticastToInterface4(ifitem->index);
1183     }
1184 }
1185
1186 void CAIPSetPacketReceiveCallback(CAIPPacketReceivedCallback callback)
1187 {
1188     g_packetReceivedCallback = callback;
1189 }
1190
1191 static void sendData(int fd, const CAEndpoint_t *endpoint,
1192                      const void *data, uint32_t dlen,
1193                      const char *cast, const char *fam)
1194 {
1195     OIC_LOG(DEBUG, TAG, "IN");
1196
1197     if (!endpoint)
1198     {
1199         OIC_LOG(DEBUG, TAG, "endpoint is null");
1200         if (g_ipErrorHandler)
1201         {
1202             g_ipErrorHandler(endpoint, data, dlen, CA_STATUS_INVALID_PARAM);
1203         }
1204         return;
1205     }
1206
1207     (void)cast;  // eliminates release warning
1208     (void)fam;
1209
1210     struct sockaddr_storage sock = { .ss_family = 0 };
1211     CAConvertNameToAddr(endpoint->addr, endpoint->port, &sock);
1212
1213     socklen_t socklen = 0;
1214     if (sock.ss_family == AF_INET6)
1215     {
1216         /** @todo figure out correct usage for ifindex, and sin6_scope_id */
1217         socklen = sizeof(struct sockaddr_in6);
1218     }
1219     else
1220     {
1221         socklen = sizeof(struct sockaddr_in);
1222     }
1223
1224 #ifdef TB_LOG
1225     const char *secure = (endpoint->flags & CA_SECURE) ? "secure " : "";
1226 #endif
1227 #if !defined(_WIN32)
1228     ssize_t len = sendto(fd, data, dlen, 0, (struct sockaddr *)&sock, socklen);
1229     if (OC_SOCKET_ERROR == len)
1230     {
1231          // If logging is not defined/enabled.
1232         if (g_ipErrorHandler)
1233         {
1234             g_ipErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
1235         }
1236         OIC_LOG_V(ERROR, TAG, "%s%s %s sendTo failed: %s", secure, cast, fam, strerror(errno));
1237     }
1238     else
1239     {
1240         OIC_LOG_V(INFO, TAG, "%s%s %s sendTo is successful: %zd bytes", secure, cast, fam, len);
1241     }
1242 #else
1243     int err = 0;
1244     int len = 0;
1245     int sent = 0;
1246     do {
1247         len = sendto(fd, ((char*)data) + sent, dlen - sent, 0, (struct sockaddr *)&sock, socklen);
1248         if (OC_SOCKET_ERROR == len)
1249         {
1250             err = WSAGetLastError();
1251             if ((WSAEWOULDBLOCK != err) && (WSAENOBUFS != err))
1252             {
1253                  // If logging is not defined/enabled.
1254                 if (g_ipErrorHandler)
1255                 {
1256                     g_ipErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
1257                 }
1258
1259                 OIC_LOG_V(ERROR, TAG, "%s%s %s sendTo failed: %i", secure, cast, fam, err);
1260             }
1261         }
1262         else
1263         {
1264             sent += len;
1265             if (sent != len)
1266             {
1267                 OIC_LOG_V(DEBUG, TAG, "%s%s %s sendTo (Partial Send) is successful: "
1268                                       "currently sent: %ld bytes, "
1269                                       "total sent: %ld bytes, "
1270                                       "remaining: %ld bytes",
1271                                       secure, cast, fam, len, sent, dlen-sent);
1272             }
1273             else
1274             {
1275                 OIC_LOG_V(INFO, TAG, "%s%s %s sendTo is successful: %ld bytes",
1276                                      secure, cast, fam, len);
1277             }
1278         }
1279     } while ((OC_SOCKET_ERROR == len) && ((WSAEWOULDBLOCK == err) || (WSAENOBUFS == err)) || (sent < dlen));
1280 #endif
1281 }
1282
1283 static void sendMulticastData6(const u_arraylist_t *iflist,
1284                                CAEndpoint_t *endpoint,
1285                                const void *data, uint32_t datalen)
1286 {
1287     if (!endpoint)
1288     {
1289         OIC_LOG(DEBUG, TAG, "endpoint is null");
1290         return;
1291     }
1292
1293     int scope = endpoint->flags & CA_SCOPE_MASK;
1294     char *ipv6mcname = ipv6mcnames[scope];
1295     if (!ipv6mcname)
1296     {
1297         OIC_LOG_V(INFO, TAG, "IPv6 multicast scope invalid: %d", scope);
1298         return;
1299     }
1300     OICStrcpy(endpoint->addr, sizeof(endpoint->addr), ipv6mcname);
1301     int fd = caglobals.ip.u6.fd;
1302
1303     uint32_t len = u_arraylist_length(iflist);
1304     for (uint32_t i = 0; i < len; i++)
1305     {
1306         CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1307         if (!ifitem)
1308         {
1309             continue;
1310         }
1311         if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
1312         {
1313             continue;
1314         }
1315         if (ifitem->family != AF_INET6)
1316         {
1317             continue;
1318         }
1319
1320         int index = ifitem->index;
1321         if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, OPTVAL_T(&index), sizeof (index)))
1322         {
1323             OIC_LOG_V(ERROR, TAG, "setsockopt6 failed: %s", CAIPS_GET_ERROR);
1324             return;
1325         }
1326         sendData(fd, endpoint, data, datalen, "multicast", "ipv6");
1327     }
1328 }
1329
1330 static void sendMulticastData4(const u_arraylist_t *iflist,
1331                                CAEndpoint_t *endpoint,
1332                                const void *data, uint32_t datalen)
1333 {
1334     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
1335
1336 #if defined(USE_IP_MREQN)
1337     struct ip_mreqn mreq = { .imr_multiaddr = IPv4MulticastAddress,
1338                              .imr_address.s_addr = htonl(INADDR_ANY),
1339                              .imr_ifindex = 0};
1340 #else
1341     struct ip_mreq mreq  = { .imr_multiaddr.s_addr = IPv4MulticastAddress.s_addr,
1342                              .imr_interface = {0}};
1343 #endif
1344
1345     OICStrcpy(endpoint->addr, sizeof(endpoint->addr), IPv4_MULTICAST);
1346     int fd = caglobals.ip.u4.fd;
1347
1348     uint32_t len = u_arraylist_length(iflist);
1349     for (uint32_t i = 0; i < len; i++)
1350     {
1351         CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1352         if (!ifitem)
1353         {
1354             continue;
1355         }
1356         if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
1357         {
1358             continue;
1359         }
1360         if (ifitem->family != AF_INET)
1361         {
1362             continue;
1363         }
1364 #if defined(USE_IP_MREQN)
1365         mreq.imr_ifindex = ifitem->index;
1366 #else
1367         mreq.imr_interface.s_addr = htonl(ifitem->index);
1368 #endif
1369         if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, OPTVAL_T(&mreq), sizeof (mreq)))
1370         {
1371             OIC_LOG_V(ERROR, TAG, "send IP_MULTICAST_IF failed: %s (using defualt)",
1372                     CAIPS_GET_ERROR);
1373         }
1374         sendData(fd, endpoint, data, datalen, "multicast", "ipv4");
1375     }
1376 }
1377
1378 void CAIPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
1379                   bool isMulticast)
1380 {
1381     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
1382     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
1383
1384     bool isSecure = (endpoint->flags & CA_SECURE) != 0;
1385
1386     if (isMulticast)
1387     {
1388         endpoint->port = isSecure ? CA_SECURE_COAP : CA_COAP;
1389
1390         u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
1391         if (!iflist)
1392         {
1393             OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
1394             return;
1395         }
1396
1397         if ((endpoint->flags & CA_IPV6) && caglobals.ip.ipv6enabled)
1398         {
1399             sendMulticastData6(iflist, endpoint, data, datalen);
1400         }
1401         if ((endpoint->flags & CA_IPV4) && caglobals.ip.ipv4enabled)
1402         {
1403             sendMulticastData4(iflist, endpoint, data, datalen);
1404         }
1405
1406         u_arraylist_destroy(iflist);
1407     }
1408     else
1409     {
1410         if (!endpoint->port)    // unicast discovery
1411         {
1412             endpoint->port = isSecure ? CA_SECURE_COAP : CA_COAP;
1413         }
1414
1415         CASocketFd_t fd;
1416         if (caglobals.ip.ipv6enabled && (endpoint->flags & CA_IPV6))
1417         {
1418             fd = isSecure ? caglobals.ip.u6s.fd : caglobals.ip.u6.fd;
1419 #ifndef __WITH_DTLS__
1420             fd = caglobals.ip.u6.fd;
1421 #endif
1422             sendData(fd, endpoint, data, datalen, "unicast", "ipv6");
1423         }
1424         if (caglobals.ip.ipv4enabled && (endpoint->flags & CA_IPV4))
1425         {
1426             fd = isSecure ? caglobals.ip.u4s.fd : caglobals.ip.u4.fd;
1427 #ifndef __WITH_DTLS__
1428             fd = caglobals.ip.u4.fd;
1429 #endif
1430             sendData(fd, endpoint, data, datalen, "unicast", "ipv4");
1431         }
1432     }
1433 }
1434
1435 CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1436 {
1437     VERIFY_NON_NULL(info, TAG, "info is NULL");
1438     VERIFY_NON_NULL(size, TAG, "size is NULL");
1439
1440     u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
1441     if (!iflist)
1442     {
1443         OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
1444         return CA_STATUS_FAILED;
1445     }
1446
1447     uint32_t len = u_arraylist_length(iflist);
1448     uint32_t length = len;
1449
1450 #ifdef __WITH_DTLS__
1451     //If DTLS is supported, each interface can support secure port as well
1452     length = len * 2;
1453 #endif
1454
1455     CAEndpoint_t *eps = (CAEndpoint_t *)OICCalloc(length, sizeof (CAEndpoint_t));
1456     if (!eps)
1457     {
1458         OIC_LOG(ERROR, TAG, "Malloc Failed");
1459         u_arraylist_destroy(iflist);
1460         return CA_MEMORY_ALLOC_FAILED;
1461     }
1462
1463     for (uint32_t i = 0, j = 0; i < len; i++)
1464     {
1465         CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1466         if(!ifitem)
1467         {
1468             continue;
1469         }
1470
1471         eps[j].adapter = CA_ADAPTER_IP;
1472         eps[j].ifindex = 0;
1473
1474         if (ifitem->family == AF_INET6)
1475         {
1476             eps[j].flags = CA_IPV6;
1477             eps[j].port = caglobals.ip.u6.port;
1478         }
1479         else
1480         {
1481             eps[j].flags = CA_IPV4;
1482             eps[j].port = caglobals.ip.u4.port;
1483         }
1484         OICStrcpy(eps[j].addr, sizeof(eps[j].addr), ifitem->addr);
1485
1486 #ifdef __WITH_DTLS__
1487         j++;
1488
1489         eps[j].adapter = CA_ADAPTER_IP;
1490         eps[j].ifindex = 0;
1491
1492         if (ifitem->family == AF_INET6)
1493         {
1494             eps[j].flags = CA_IPV6 | CA_SECURE;
1495             eps[j].port = caglobals.ip.u6s.port;
1496         }
1497         else
1498         {
1499             eps[j].flags = CA_IPV4 | CA_SECURE;
1500             eps[j].port = caglobals.ip.u4s.port;
1501         }
1502         OICStrcpy(eps[j].addr, sizeof(eps[j].addr), ifitem->addr);
1503 #endif
1504         j++;
1505     }
1506
1507     *info = eps;
1508     *size = length;
1509
1510     u_arraylist_destroy(iflist);
1511
1512     return CA_STATUS_OK;
1513 }
1514
1515 void CAIPSetErrorHandler(CAIPErrorHandleCallback errorHandleCallback)
1516 {
1517     g_ipErrorHandler = errorHandleCallback;
1518 }