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