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