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