Merge branch 'master' into windows-port
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / ip_adapter / caipserver.c
1 /*****************************************************************j
2  *
3  * Copyright 2014 Samsung Electronics All Rights Reserved.
4  *
5  *
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  ******************************************************************/
20
21 #ifndef __APPLE_USE_RFC_3542
22 #define __APPLE_USE_RFC_3542 // for PKTINFO
23 #endif
24 #ifndef _GNU_SOURCE
25 #define _GNU_SOURCE // for in6_pktinfo
26 #endif
27
28 #include <sys/types.h>
29 #include <sys/socket.h>
30 #include <stdio.h>
31 #include <unistd.h>
32 #include <sys/types.h>
33 #include <fcntl.h>
34 #include <sys/select.h>
35 #include <arpa/inet.h>
36 #include <netinet/in.h>
37 #include <net/if.h>
38 #include <errno.h>
39 #ifdef __linux__
40 #include <linux/netlink.h>
41 #include <linux/rtnetlink.h>
42 #endif
43
44 #include "pdu.h"
45 #include "caipinterface.h"
46 #include "caadapterutils.h"
47 #ifdef __WITH_DTLS__
48 #include "caadapternetdtls.h"
49 #endif
50 #include "camutex.h"
51 #include "oic_malloc.h"
52 #include "oic_string.h"
53
54 /*
55  * Logging tag for module name
56  */
57 #define TAG "OIC_CA_IP_SERVER"
58
59 #define SELECT_TIMEOUT 1     // select() seconds (and termination latency)
60
61 #define IPv4_MULTICAST     "224.0.1.187"
62 static struct in_addr IPv4MulticastAddress = { 0 };
63
64 #define IPv6_DOMAINS       16
65 #define IPv6_MULTICAST_INT "ff01::fd"
66 static struct in6_addr IPv6MulticastAddressInt;
67 #define IPv6_MULTICAST_LNK "ff02::fd"
68 static struct in6_addr IPv6MulticastAddressLnk;
69 #define IPv6_MULTICAST_RLM "ff03::fd"
70 static struct in6_addr IPv6MulticastAddressRlm;
71 #define IPv6_MULTICAST_ADM "ff04::fd"
72 static struct in6_addr IPv6MulticastAddressAdm;
73 #define IPv6_MULTICAST_SIT "ff05::fd"
74 static struct in6_addr IPv6MulticastAddressSit;
75 #define IPv6_MULTICAST_ORG "ff08::fd"
76 static struct in6_addr IPv6MulticastAddressOrg;
77 #define IPv6_MULTICAST_GLB "ff0e::fd"
78 static struct in6_addr IPv6MulticastAddressGlb;
79
80 static char *ipv6mcnames[IPv6_DOMAINS] = {
81     NULL,
82     IPv6_MULTICAST_INT,
83     IPv6_MULTICAST_LNK,
84     IPv6_MULTICAST_RLM,
85     IPv6_MULTICAST_ADM,
86     IPv6_MULTICAST_SIT,
87     NULL,
88     NULL,
89     IPv6_MULTICAST_ORG,
90     NULL,
91     NULL,
92     NULL,
93     NULL,
94     NULL,
95     IPv6_MULTICAST_GLB,
96     NULL
97 };
98
99 static CAIPExceptionCallback g_exceptionCallback;
100
101 static CAIPPacketReceivedCallback g_packetReceivedCallback;
102
103 static void CAHandleNetlink();
104 static void CAFindReadyMessage();
105 static void CASelectReturned(fd_set *readFds, int ret);
106 static void CAProcessNewInterface(CAInterface_t *ifchanged);
107 static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags);
108
109 #define SET(TYPE, FDS) \
110     if (caglobals.ip.TYPE.fd != -1) \
111     { \
112         FD_SET(caglobals.ip.TYPE.fd, FDS); \
113     }
114
115 #define ISSET(TYPE, FDS, FLAGS) \
116     if (caglobals.ip.TYPE.fd != -1 && FD_ISSET(caglobals.ip.TYPE.fd, FDS)) \
117     { \
118         fd = caglobals.ip.TYPE.fd; \
119         flags = FLAGS; \
120     }
121
122 #define CLOSE_SOCKET(TYPE) \
123     if (caglobals.ip.TYPE.fd != -1) \
124     { \
125         close(caglobals.ip.TYPE.fd); \
126         caglobals.ip.TYPE.fd = -1; \
127     }
128
129 void CADeInitializeIPGlobals()
130 {
131     CLOSE_SOCKET(u6);
132     CLOSE_SOCKET(u6s);
133     CLOSE_SOCKET(u4);
134     CLOSE_SOCKET(u4s);
135     CLOSE_SOCKET(m6);
136     CLOSE_SOCKET(m6s);
137     CLOSE_SOCKET(m4);
138     CLOSE_SOCKET(m4s);
139
140     if (caglobals.ip.netlinkFd != -1)
141     {
142         close(caglobals.ip.netlinkFd);
143         caglobals.ip.netlinkFd = -1;
144     }
145 }
146
147 static void CAReceiveHandler(void *data)
148 {
149     (void)data;
150
151     while (!caglobals.ip.terminate)
152     {
153         CAFindReadyMessage();
154     }
155 }
156
157 static void CAFindReadyMessage()
158 {
159     fd_set readFds;
160     struct timeval timeout;
161
162     timeout.tv_sec = caglobals.ip.selectTimeout;
163     timeout.tv_usec = 0;
164     struct timeval *tv = caglobals.ip.selectTimeout == -1 ? NULL : &timeout;
165
166     FD_ZERO(&readFds);
167     SET(u6,  &readFds)
168     SET(u6s, &readFds)
169     SET(u4,  &readFds)
170     SET(u4s, &readFds)
171     SET(m6,  &readFds)
172     SET(m6s, &readFds)
173     SET(m4,  &readFds)
174     SET(m4s, &readFds)
175     if (caglobals.ip.shutdownFds[0] != -1)
176     {
177         FD_SET(caglobals.ip.shutdownFds[0], &readFds);
178     }
179     if (caglobals.ip.netlinkFd != -1)
180     {
181         FD_SET(caglobals.ip.netlinkFd, &readFds);
182     }
183
184     int ret = select(caglobals.ip.maxfd + 1, &readFds, NULL, NULL, tv);
185
186     if (caglobals.ip.terminate)
187     {
188         OIC_LOG_V(DEBUG, TAG, "Packet receiver Stop request received.");
189         return;
190     }
191     if (ret <= 0)
192     {
193         if (ret < 0)
194         {
195             OIC_LOG_V(FATAL, TAG, "select error %s", strerror(errno));
196         }
197         return;
198     }
199
200     CASelectReturned(&readFds, ret);
201 }
202
203 static void CASelectReturned(fd_set *readFds, int ret)
204 {
205     (void)ret;
206     int fd = -1;
207     CATransportFlags_t flags = CA_DEFAULT_FLAGS;
208
209     while (!caglobals.ip.terminate)
210     {
211         ISSET(u6,  readFds, CA_IPV6)
212         else ISSET(u6s, readFds, CA_IPV6 | CA_SECURE)
213         else ISSET(u4,  readFds, CA_IPV4)
214         else ISSET(u4s, readFds, CA_IPV4 | CA_SECURE)
215         else ISSET(m6,  readFds, CA_MULTICAST | CA_IPV6)
216         else ISSET(m6s, readFds, CA_MULTICAST | CA_IPV6 | CA_SECURE)
217         else ISSET(m4,  readFds, CA_MULTICAST | CA_IPV4)
218         else ISSET(m4s, readFds, CA_MULTICAST | CA_IPV4 | CA_SECURE)
219         else if (FD_ISSET(caglobals.ip.netlinkFd, readFds))
220         {
221             CAInterface_t *ifchanged = CAFindInterfaceChange();
222             if (ifchanged)
223             {
224                 CAProcessNewInterface(ifchanged);
225                 OICFree(ifchanged);
226             }
227             break;
228         }
229         else if (FD_ISSET(caglobals.ip.shutdownFds[0], readFds))
230         {
231             char buf[10] = {0};
232             ssize_t len = read(caglobals.ip.shutdownFds[0], buf, sizeof (buf));
233             if (-1 == len)
234             {
235                 continue;
236             }
237             break;
238         }
239         else
240         {
241             break;
242         }
243
244         (void)CAReceiveMessage(fd, flags);
245         FD_CLR(fd, readFds);
246     }
247 }
248
249 static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags)
250 {
251     char recvBuffer[COAP_MAX_PDU_SIZE];
252
253     size_t len;
254     int level, type, namelen;
255     struct sockaddr_storage srcAddr;
256     unsigned char *pktinfo = NULL;
257     struct cmsghdr *cmp = NULL;
258     struct iovec iov = { recvBuffer, sizeof (recvBuffer) };
259     union control
260     {
261         struct cmsghdr cmsg;
262         unsigned char data[CMSG_SPACE(sizeof (struct in6_pktinfo))];
263     } cmsg;
264
265     if (flags & CA_IPV6)
266     {
267         namelen = sizeof (struct sockaddr_in6);
268         level = IPPROTO_IPV6;
269         type = IPV6_PKTINFO;
270         len = sizeof (struct in6_pktinfo);
271     }
272     else
273     {
274         namelen = sizeof (struct sockaddr_in);
275         level = IPPROTO_IP;
276         type = IP_PKTINFO;
277         len = sizeof (struct in6_pktinfo);
278     }
279
280     struct msghdr msg = { .msg_name = &srcAddr,
281                           .msg_namelen = namelen,
282                           .msg_iov = &iov,
283                           .msg_iovlen = 1,
284                           .msg_control = &cmsg,
285                           .msg_controllen = CMSG_SPACE(len) };
286
287     ssize_t recvLen = recvmsg(fd, &msg, flags);
288     if (-1 == recvLen)
289     {
290         OIC_LOG_V(ERROR, TAG, "Recvfrom failed %s", strerror(errno));
291         return CA_STATUS_FAILED;
292     }
293
294     if (flags & CA_MULTICAST)
295     {
296         for (cmp = CMSG_FIRSTHDR(&msg); cmp != NULL; cmp = CMSG_NXTHDR(&msg, cmp))
297         {
298             if (cmp->cmsg_level == level && cmp->cmsg_type == type)
299             {
300                 pktinfo = CMSG_DATA(cmp);
301             }
302         }
303     }
304
305     CASecureEndpoint_t sep = {.endpoint = {.adapter = CA_ADAPTER_IP, .flags = flags}};
306
307     if (flags & CA_IPV6)
308     {
309         sep.endpoint.ifindex = ((struct sockaddr_in6 *)&srcAddr)->sin6_scope_id;
310         ((struct sockaddr_in6 *)&srcAddr)->sin6_scope_id = 0;
311
312         if ((flags & CA_MULTICAST) && pktinfo)
313         {
314             struct in6_addr *addr = &(((struct in6_pktinfo *)pktinfo)->ipi6_addr);
315             unsigned char topbits = ((unsigned char *)addr)[0];
316             if (topbits != 0xff)
317             {
318                 sep.endpoint.flags &= ~CA_MULTICAST;
319             }
320         }
321     }
322     else
323     {
324         if ((flags & CA_MULTICAST) && pktinfo)
325         {
326             struct in_addr *addr = &((struct in_pktinfo *)pktinfo)->ipi_addr;
327             uint32_t host = ntohl(addr->s_addr);
328             unsigned char topbits = ((unsigned char *)&host)[3];
329             if (topbits < 224 || topbits > 239)
330             {
331                 sep.endpoint.flags &= ~CA_MULTICAST;
332             }
333         }
334     }
335
336     CAConvertAddrToName(&srcAddr, msg.msg_namelen, sep.endpoint.addr, &sep.endpoint.port);
337
338     if (flags & CA_SECURE)
339     {
340 #ifdef __WITH_DTLS__
341         int ret = CAAdapterNetDtlsDecrypt(&sep, (uint8_t *)recvBuffer, recvLen);
342         OIC_LOG_V(DEBUG, TAG, "CAAdapterNetDtlsDecrypt returns [%d]", ret);
343 #else
344         OIC_LOG(ERROR, TAG, "Encrypted message but no DTLS");
345 #endif
346     }
347     else
348     {
349         if (g_packetReceivedCallback)
350         {
351             g_packetReceivedCallback(&sep, recvBuffer, recvLen);
352         }
353     }
354
355     return CA_STATUS_OK;
356 }
357
358 void CAIPPullData()
359 {
360     OIC_LOG(DEBUG, TAG, "IN");
361     OIC_LOG(DEBUG, TAG, "OUT");
362 }
363
364 static int CACreateSocket(int family, uint16_t *port)
365 {
366     int socktype = SOCK_DGRAM;
367 #ifdef SOCK_CLOEXEC
368     socktype |= SOCK_CLOEXEC;
369 #endif
370     int fd = socket(family, socktype, IPPROTO_UDP);
371     if (-1 == fd)
372     {
373         OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
374         return -1;
375     }
376
377 #ifndef SOCK_CLOEXEC
378     int fl = fcntl(fd, F_GETFD);
379     if (-1 == fl || -1 == fcntl(fd, F_SETFD, fl|FD_CLOEXEC))
380     {
381         OIC_LOG_V(ERROR, TAG, "set FD_CLOEXEC failed: %s", strerror(errno));
382         close(fd);
383         return -1;
384     }
385 #endif
386
387     struct sockaddr_storage sa = { .ss_family = family };
388     socklen_t socklen;
389
390     if (family == AF_INET6)
391     {
392         int on = 1;
393
394         if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
395         {
396             OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
397         }
398
399         if (*port)      // only do this for multicast ports
400         {
401             if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof (on)))
402             {
403                 OIC_LOG_V(ERROR, TAG, "IPV6_RECVPKTINFO failed: %s", strerror(errno));
404             }
405         }
406
407         ((struct sockaddr_in6 *)&sa)->sin6_port = htons(*port);
408         socklen = sizeof (struct sockaddr_in6);
409     }
410     else
411     {
412         if (*port)      // only do this for multicast ports
413         {
414             int on = 1;
415             if (-1 == setsockopt(fd, IPPROTO_IP, IP_PKTINFO, &on, sizeof (on)))
416             {
417                 OIC_LOG_V(ERROR, TAG, "IP_PKTINFO failed: %s", strerror(errno));
418             }
419         }
420
421         ((struct sockaddr_in *)&sa)->sin_port = htons(*port);
422         socklen = sizeof (struct sockaddr_in);
423     }
424
425     if (*port)  // use the given port
426     {
427         int on = 1;
428         if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof (on)))
429         {
430             OIC_LOG_V(ERROR, TAG, "SO_REUSEADDR failed: %s", strerror(errno));
431             close(fd);
432             return -1;
433         }
434     }
435
436     if (-1 == bind(fd, (struct sockaddr *)&sa, socklen))
437     {
438         OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
439         close(fd);
440         return -1;
441     }
442
443     if (!*port)  // return the assigned port
444     {
445         if (-1 == getsockname(fd, (struct sockaddr *)&sa, &socklen))
446         {
447             OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
448             close(fd);
449             return -1;
450         }
451         *port = ntohs(family == AF_INET6 ?
452                       ((struct sockaddr_in6 *)&sa)->sin6_port :
453                       ((struct sockaddr_in *)&sa)->sin_port);
454     }
455
456     return fd;
457 }
458
459 #define CHECKFD(FD) \
460     if (FD > caglobals.ip.maxfd) \
461         caglobals.ip.maxfd = FD;
462 #define NEWSOCKET(FAMILY, NAME) \
463     caglobals.ip.NAME.fd = CACreateSocket(FAMILY, &caglobals.ip.NAME.port); \
464     CHECKFD(caglobals.ip.NAME.fd)
465
466 static void CAInitializeNetlink()
467 {
468 #ifdef __linux__
469     // create NETLINK fd for interface change notifications
470     struct sockaddr_nl sa = { AF_NETLINK, 0, 0, RTMGRP_LINK };
471
472     caglobals.ip.netlinkFd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC, NETLINK_ROUTE);
473     if (caglobals.ip.netlinkFd == -1)
474     {
475         OIC_LOG_V(ERROR, TAG, "netlink socket failed: %s", strerror(errno));
476     }
477     else
478     {
479         int r = bind(caglobals.ip.netlinkFd, (struct sockaddr *)&sa, sizeof (sa));
480         if (r)
481         {
482             OIC_LOG_V(ERROR, TAG, "netlink bind failed: %s", strerror(errno));
483             close(caglobals.ip.netlinkFd);
484             caglobals.ip.netlinkFd = -1;
485         }
486         else
487         {
488             CHECKFD(caglobals.ip.netlinkFd);
489         }
490     }
491 #endif
492 }
493
494 static void CAInitializePipe()
495 {
496     caglobals.ip.selectTimeout = -1;
497 #ifdef HAVE_PIPE2
498     int ret = pipe2(caglobals.ip.shutdownFds, O_CLOEXEC);
499 #else
500     int ret = pipe(caglobals.ip.shutdownFds);
501     if (-1 != ret)
502     {
503         ret = fcntl(caglobals.ip.shutdownFds[0], F_GETFD);
504         if (-1 != ret)
505         {
506             ret = fcntl(caglobals.ip.shutdownFds[0], F_SETFD, ret|FD_CLOEXEC);
507         }
508         if (-1 != ret)
509         {
510             ret = fcntl(caglobals.ip.shutdownFds[1], F_GETFD);
511         }
512         if (-1 != ret)
513         {
514             ret = fcntl(caglobals.ip.shutdownFds[1], F_SETFD, ret|FD_CLOEXEC);
515         }
516         if (-1 == ret)
517         {
518             close(caglobals.ip.shutdownFds[1]);
519             close(caglobals.ip.shutdownFds[0]);
520             caglobals.ip.shutdownFds[0] = -1;
521             caglobals.ip.shutdownFds[1] = -1;
522         }
523     }
524 #endif
525     if (-1 == ret)
526     {
527         OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
528         caglobals.ip.selectTimeout = SELECT_TIMEOUT; //poll needed for shutdown
529     }
530 }
531
532 CAResult_t CAIPStartServer(const ca_thread_pool_t threadPool)
533 {
534     CAResult_t res = CA_STATUS_OK;
535
536     if (caglobals.ip.started)
537     {
538         return res;
539     }
540
541     if (!IPv4MulticastAddress.s_addr)
542     {
543         (void)inet_pton(AF_INET, IPv4_MULTICAST, &IPv4MulticastAddress);
544         (void)inet_pton(AF_INET6, IPv6_MULTICAST_INT, &IPv6MulticastAddressInt);
545         (void)inet_pton(AF_INET6, IPv6_MULTICAST_LNK, &IPv6MulticastAddressLnk);
546         (void)inet_pton(AF_INET6, IPv6_MULTICAST_RLM, &IPv6MulticastAddressRlm);
547         (void)inet_pton(AF_INET6, IPv6_MULTICAST_ADM, &IPv6MulticastAddressAdm);
548         (void)inet_pton(AF_INET6, IPv6_MULTICAST_SIT, &IPv6MulticastAddressSit);
549         (void)inet_pton(AF_INET6, IPv6_MULTICAST_ORG, &IPv6MulticastAddressOrg);
550         (void)inet_pton(AF_INET6, IPv6_MULTICAST_GLB, &IPv6MulticastAddressGlb);
551     }
552
553     if (!caglobals.ip.ipv6enabled && !caglobals.ip.ipv4enabled)
554     {
555         caglobals.ip.ipv4enabled = true;  // only needed to run CA tests
556     }
557
558     if (caglobals.ip.ipv6enabled)
559     {
560         NEWSOCKET(AF_INET6, u6)
561         NEWSOCKET(AF_INET6, u6s)
562         NEWSOCKET(AF_INET6, m6)
563         NEWSOCKET(AF_INET6, m6s)
564         OIC_LOG_V(INFO, TAG, "IPv6 unicast port: %u", caglobals.ip.u6.port);
565     }
566     if (caglobals.ip.ipv4enabled)
567     {
568         NEWSOCKET(AF_INET, u4)
569         NEWSOCKET(AF_INET, u4s)
570         NEWSOCKET(AF_INET, m4)
571         NEWSOCKET(AF_INET, m4s)
572         OIC_LOG_V(INFO, TAG, "IPv4 unicast port: %u", caglobals.ip.u4.port);
573     }
574
575     OIC_LOG_V(DEBUG, TAG,
576               "socket summary: u6=%d, u6s=%d, u4=%d, u4s=%d, m6=%d, m6s=%d, m4=%d, m4s=%d",
577               caglobals.ip.u6.fd, caglobals.ip.u6s.fd, caglobals.ip.u4.fd, caglobals.ip.u4s.fd,
578               caglobals.ip.m6.fd, caglobals.ip.m6s.fd, caglobals.ip.m4.fd, caglobals.ip.m4s.fd);
579
580     OIC_LOG_V(DEBUG, TAG,
581               "port summary: u6 port=%d, u6s port=%d, u4 port=%d, u4s port=%d, m6 port=%d,"
582               "m6s port=%d, m4 port=%d, m4s port=%d",
583               caglobals.ip.u6.port, caglobals.ip.u6s.port, caglobals.ip.u4.port,
584               caglobals.ip.u4s.port, caglobals.ip.m6.port, caglobals.ip.m6s.port,
585               caglobals.ip.m4.port, caglobals.ip.m4s.port);
586     // create pipe for fast shutdown
587     CAInitializePipe();
588     CHECKFD(caglobals.ip.shutdownFds[0]);
589     CHECKFD(caglobals.ip.shutdownFds[1]);
590
591     // create source of network interface change notifications
592     CAInitializeNetlink();
593
594     caglobals.ip.selectTimeout = CAGetPollingInterval(caglobals.ip.selectTimeout);
595
596     res = CAIPStartListenServer();
597     if (CA_STATUS_OK != res)
598     {
599         OIC_LOG_V(ERROR, TAG, "Failed to start listening server![%d]", res);
600         return res;
601     }
602
603     caglobals.ip.terminate = false;
604     res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
605     if (CA_STATUS_OK != res)
606     {
607         OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
608         return res;
609     }
610     OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
611
612     caglobals.ip.started = true;
613     return CA_STATUS_OK;
614 }
615
616 void CAIPStopServer()
617 {
618     caglobals.ip.started = false;
619     caglobals.ip.terminate = true;
620
621     if (caglobals.ip.shutdownFds[1] != -1)
622     {
623         close(caglobals.ip.shutdownFds[1]);
624         // receive thread will stop immediately
625     }
626     else
627     {
628         // receive thread will stop in SELECT_TIMEOUT seconds.
629     }
630 }
631
632 void CAWakeUpForChange()
633 {
634     if (caglobals.ip.shutdownFds[1] != -1)
635     {
636         ssize_t len = 0;
637         do
638         {
639             len = write(caglobals.ip.shutdownFds[1], "w", 1);
640         } while ((len == -1) && (errno == EINTR));
641         if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
642         {
643             OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
644         }
645     }
646 }
647
648 static void applyMulticastToInterface4(struct in_addr inaddr)
649 {
650     if (!caglobals.ip.ipv4enabled)
651     {
652         return;
653     }
654
655     struct ip_mreqn mreq = { .imr_multiaddr = IPv4MulticastAddress,
656                              .imr_address = inaddr,
657                              .imr_ifindex = 0 };
658     if (setsockopt(caglobals.ip.m4.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof (mreq)))
659     {
660         if (EADDRINUSE != errno)
661         {
662             OIC_LOG_V(ERROR, TAG, "IPv4 IP_ADD_MEMBERSHIP failed: %s", strerror(errno));
663         }
664     }
665     if (setsockopt(caglobals.ip.m4s.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof (mreq)))
666     {
667         if (EADDRINUSE != errno)
668         {
669             OIC_LOG_V(ERROR, TAG, "secure IPv4 IP_ADD_MEMBERSHIP failed: %s", strerror(errno));
670         }
671     }
672 }
673
674 static void applyMulticast6(int fd, struct in6_addr *addr, uint32_t ifindex)
675 {
676     struct ipv6_mreq mreq = {.ipv6mr_multiaddr = *addr, .ipv6mr_interface = ifindex};
677     if (setsockopt(fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq, sizeof (mreq)))
678     {
679         if (EADDRINUSE != errno)
680         {
681             OIC_LOG_V(ERROR, TAG, "IPv6 IP_ADD_MEMBERSHIP failed: %s", strerror(errno));
682         }
683     }
684 }
685
686 static void applyMulticastToInterface6(uint32_t ifindex)
687 {
688     if (!caglobals.ip.ipv6enabled)
689     {
690         return;
691     }
692     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressInt, ifindex);
693     applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressLnk, ifindex);
694     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressRlm, ifindex);
695     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressAdm, ifindex);
696     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressSit, ifindex);
697     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressOrg, ifindex);
698     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressGlb, ifindex);
699
700     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressInt, ifindex);
701     applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressLnk, ifindex);
702     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressRlm, ifindex);
703     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressAdm, ifindex);
704     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressSit, ifindex);
705     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressOrg, ifindex);
706     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressGlb, ifindex);
707 }
708
709 CAResult_t CAIPStartListenServer()
710 {
711     u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
712     if (!iflist)
713     {
714         OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
715         return CA_STATUS_FAILED;
716     }
717
718     uint32_t len = u_arraylist_length(iflist);
719     OIC_LOG_V(DEBUG, TAG, "IP network interfaces found: %d", len);
720
721     for (uint32_t i = 0; i < len; i++)
722     {
723         CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
724
725         if (!ifitem)
726         {
727             continue;
728         }
729         if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
730         {
731             continue;
732         }
733         if (ifitem->family == AF_INET)
734         {
735             struct in_addr inaddr;
736             inaddr.s_addr = ifitem->ipv4addr;
737             applyMulticastToInterface4(inaddr);
738             OIC_LOG_V(DEBUG, TAG, "IPv4 network interface: %s", ifitem->name);
739         }
740         if (ifitem->family == AF_INET6)
741         {
742             applyMulticastToInterface6(ifitem->index);
743             OIC_LOG_V(DEBUG, TAG, "IPv6 network interface: %s", ifitem->name);
744         }
745     }
746
747     u_arraylist_destroy(iflist);
748     return CA_STATUS_OK;
749 }
750
751 CAResult_t CAIPStopListenServer()
752 {
753     u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
754     if (!iflist)
755     {
756         OIC_LOG_V(ERROR, TAG, "Get interface info failed: %s", strerror(errno));
757         return CA_STATUS_FAILED;
758     }
759
760     uint32_t len = u_arraylist_length(iflist);
761     OIC_LOG_V(DEBUG, TAG, "IP network interfaces found: %d", len);
762
763     for (uint32_t i = 0; i < len; i++)
764     {
765         CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
766
767         if (!ifitem)
768         {
769             continue;
770         }
771
772         if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
773         {
774             continue;
775         }
776         if (ifitem->family == AF_INET)
777         {
778             close(caglobals.ip.m4.fd);
779             close(caglobals.ip.m4s.fd);
780             caglobals.ip.m4.fd = -1;
781             caglobals.ip.m4s.fd = -1;
782             OIC_LOG_V(DEBUG, TAG, "IPv4 network interface: %s cloed", ifitem->name);
783         }
784         if (ifitem->family == AF_INET6)
785         {
786             close(caglobals.ip.m6.fd);
787             close(caglobals.ip.m6s.fd);
788             caglobals.ip.m6.fd = -1;
789             caglobals.ip.m6s.fd = -1;
790             OIC_LOG_V(DEBUG, TAG, "IPv6 network interface: %s", ifitem->name);
791         }
792     }
793     u_arraylist_destroy(iflist);
794     return CA_STATUS_OK;
795 }
796
797 static void CAProcessNewInterface(CAInterface_t *ifitem)
798 {
799     if (!ifitem)
800     {
801         OIC_LOG(DEBUG, TAG, "ifitem is null");
802         return;
803     }
804     if (ifitem->family == AF_INET6)
805     {
806         applyMulticastToInterface6(ifitem->index);
807     }
808     if (ifitem->family == AF_INET)
809     {
810         struct in_addr inaddr = { .s_addr = ifitem->ipv4addr };
811         applyMulticastToInterface4(inaddr);
812     }
813 }
814
815 void CAIPSetPacketReceiveCallback(CAIPPacketReceivedCallback callback)
816 {
817     g_packetReceivedCallback = callback;
818 }
819
820 void CAIPSetExceptionCallback(CAIPExceptionCallback callback)
821 {
822     g_exceptionCallback = callback;
823 }
824
825 void CAIPSetConnectionStateChangeCallback(CAIPConnectionStateChangeCallback callback)
826 {
827     CAIPSetNetworkMonitorCallback(callback);
828 }
829
830 static void sendData(int fd, const CAEndpoint_t *endpoint,
831                      const void *data, uint32_t dlen,
832                      const char *cast, const char *fam)
833 {
834     OIC_LOG(DEBUG, TAG, "IN");
835
836     if (!endpoint)
837     {
838         OIC_LOG(DEBUG, TAG, "endpoint is null");
839         return;
840     }
841
842     char *secure = (endpoint->flags & CA_SECURE) ? "secure " : "";
843     (void)secure;   // eliminates release warning
844     struct sockaddr_storage sock;
845     CAConvertNameToAddr(endpoint->addr, endpoint->port, &sock);
846
847     socklen_t socklen;
848     if (sock.ss_family == AF_INET6)
849     {
850         struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sock;
851         if (!sock6->sin6_scope_id)
852         {
853             sock6->sin6_scope_id = endpoint->ifindex;
854         }
855         socklen = sizeof(struct sockaddr_in6);
856     }
857     else
858     {
859         socklen = sizeof(struct sockaddr_in);
860     }
861
862     ssize_t len = sendto(fd, data, dlen, 0, (struct sockaddr *)&sock, socklen);
863     if (-1 == len)
864     {
865          // If logging is not defined/enabled.
866         (void)cast;
867         (void)fam;
868         OIC_LOG_V(ERROR, TAG, "%s%s %s sendTo failed: %s", secure, cast, fam, strerror(errno));
869     }
870     else
871     {
872         OIC_LOG_V(INFO, TAG, "%s%s %s sendTo is successful: %zd bytes", secure, cast, fam, len);
873     }
874 }
875
876 static void sendMulticastData6(const u_arraylist_t *iflist,
877                                CAEndpoint_t *endpoint,
878                                const void *data, uint32_t datalen)
879 {
880     if (!endpoint)
881     {
882         OIC_LOG(DEBUG, TAG, "endpoint is null");
883         return;
884     }
885
886     int scope = endpoint->flags & CA_SCOPE_MASK;
887     char *ipv6mcname = ipv6mcnames[scope];
888     if (!ipv6mcname)
889     {
890         OIC_LOG_V(INFO, TAG, "IPv6 multicast scope invalid: %d", scope);
891         return;
892     }
893     OICStrcpy(endpoint->addr, sizeof(endpoint->addr), ipv6mcname);
894     int fd = caglobals.ip.u6.fd;
895
896     uint32_t len = u_arraylist_length(iflist);
897     for (uint32_t i = 0; i < len; i++)
898     {
899         CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
900         if (!ifitem)
901         {
902             continue;
903         }
904         if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
905         {
906             continue;
907         }
908         if (ifitem->family != AF_INET6)
909         {
910             continue;
911         }
912
913         int index = ifitem->index;
914         if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, &index, sizeof (index)))
915         {
916             OIC_LOG_V(ERROR, TAG, "setsockopt6 failed: %s", strerror(errno));
917             return;
918         }
919         sendData(fd, endpoint, data, datalen, "multicast", "ipv6");
920     }
921 }
922
923 static void sendMulticastData4(const u_arraylist_t *iflist,
924                                CAEndpoint_t *endpoint,
925                                const void *data, uint32_t datalen)
926 {
927     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
928
929     struct ip_mreqn mreq = { .imr_multiaddr = IPv4MulticastAddress,
930                              .imr_ifindex = 0 };
931     OICStrcpy(endpoint->addr, sizeof(endpoint->addr), IPv4_MULTICAST);
932     int fd = caglobals.ip.u4.fd;
933
934     uint32_t len = u_arraylist_length(iflist);
935     for (uint32_t i = 0; i < len; i++)
936     {
937         CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
938         if (!ifitem)
939         {
940             continue;
941         }
942         if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
943         {
944             continue;
945         }
946         if (ifitem->family != AF_INET)
947         {
948             continue;
949         }
950
951         struct in_addr inaddr;
952         inaddr.s_addr = ifitem->ipv4addr;
953         mreq.imr_address = inaddr;
954         if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, &mreq, sizeof (mreq)))
955         {
956             OIC_LOG_V(ERROR, TAG, "send IP_MULTICAST_IF failed: %s (using defualt)",
957                     strerror(errno));
958         }
959         sendData(fd, endpoint, data, datalen, "multicast", "ipv4");
960     }
961 }
962
963 void CAIPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
964                   bool isMulticast)
965 {
966     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
967     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
968
969     bool isSecure = (endpoint->flags & CA_SECURE) != 0;
970
971     if (isMulticast)
972     {
973         endpoint->port = isSecure ? CA_SECURE_COAP : CA_COAP;
974
975         u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
976         if (!iflist)
977         {
978             OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
979             return;
980         }
981
982         if ((endpoint->flags & CA_IPV6) && caglobals.ip.ipv6enabled)
983         {
984             sendMulticastData6(iflist, endpoint, data, datalen);
985         }
986         if ((endpoint->flags & CA_IPV4) && caglobals.ip.ipv4enabled)
987         {
988             sendMulticastData4(iflist, endpoint, data, datalen);
989         }
990
991         u_arraylist_destroy(iflist);
992     }
993     else
994     {
995         if (!endpoint->port)    // unicast discovery
996         {
997             endpoint->port = isSecure ? CA_SECURE_COAP : CA_COAP;
998         }
999
1000         int fd;
1001         if (caglobals.ip.ipv6enabled && (endpoint->flags & CA_IPV6))
1002         {
1003             fd = isSecure ? caglobals.ip.u6s.fd : caglobals.ip.u6.fd;
1004 #ifndef __WITH_DTLS__
1005             fd = caglobals.ip.u6.fd;
1006 #endif
1007             sendData(fd, endpoint, data, datalen, "unicast", "ipv6");
1008         }
1009         if (caglobals.ip.ipv4enabled && (endpoint->flags & CA_IPV4))
1010         {
1011             fd = isSecure ? caglobals.ip.u4s.fd : caglobals.ip.u4.fd;
1012 #ifndef __WITH_DTLS__
1013             fd = caglobals.ip.u4.fd;
1014 #endif
1015             sendData(fd, endpoint, data, datalen, "unicast", "ipv4");
1016         }
1017     }
1018 }
1019
1020 CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1021 {
1022     VERIFY_NON_NULL(info, TAG, "info is NULL");
1023     VERIFY_NON_NULL(size, TAG, "size is NULL");
1024
1025     u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
1026     if (!iflist)
1027     {
1028         OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
1029         return CA_STATUS_FAILED;
1030     }
1031
1032     uint32_t len = u_arraylist_length(iflist);
1033     uint32_t length = len;
1034
1035 #ifdef __WITH_DTLS__
1036     //If DTLS is supported, each interface can support secure port as well
1037     length = len * 2;
1038 #endif
1039
1040     CAEndpoint_t *eps = (CAEndpoint_t *)OICCalloc(length, sizeof (CAEndpoint_t));
1041     if (!eps)
1042     {
1043         OIC_LOG(ERROR, TAG, "Malloc Failed");
1044         u_arraylist_destroy(iflist);
1045         return CA_MEMORY_ALLOC_FAILED;
1046     }
1047
1048     for (uint32_t i = 0, j = 0; i < len; i++)
1049     {
1050         CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1051         if(!ifitem)
1052         {
1053             continue;
1054         }
1055
1056         eps[j].adapter = CA_ADAPTER_IP;
1057         eps[j].ifindex = 0;
1058
1059         if (ifitem->family == AF_INET6)
1060         {
1061             eps[j].flags = CA_IPV6;
1062             eps[j].port = caglobals.ip.u6.port;
1063         }
1064         else
1065         {
1066             eps[j].flags = CA_IPV4;
1067             eps[j].port = caglobals.ip.u4.port;
1068
1069             inet_ntop(AF_INET, &(ifitem->ipv4addr), eps[j].addr, MAX_ADDR_STR_SIZE_CA);
1070         }
1071
1072 #ifdef __WITH_DTLS__
1073         j++;
1074
1075         eps[j].adapter = CA_ADAPTER_IP;
1076         eps[j].ifindex = 0;
1077
1078         if (ifitem->family == AF_INET6)
1079         {
1080             eps[j].flags = CA_IPV6 | CA_SECURE;
1081             eps[j].port = caglobals.ip.u6s.port;
1082         }
1083         else
1084         {
1085             eps[j].flags = CA_IPV4 | CA_SECURE;
1086             eps[j].port = caglobals.ip.u4s.port;
1087             inet_ntop(AF_INET, &(ifitem->ipv4addr), eps[j].addr, MAX_ADDR_STR_SIZE_CA);
1088         }
1089 #endif
1090         j++;
1091     }
1092
1093     *info = eps;
1094     *size = len;
1095
1096     u_arraylist_destroy(iflist);
1097
1098     return CA_STATUS_OK;
1099 }