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