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