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