Merge branch 'master' into notification-service
[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.interface = ((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 interface)
707 {
708     struct ipv6_mreq mreq = {.ipv6mr_multiaddr = *addr, .ipv6mr_interface = interface};
709
710     if (setsockopt(fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq, sizeof (mreq)))
711     {
712         if (EADDRINUSE != errno)
713         {
714             OIC_LOG_V(ERROR, TAG, "IPv6 IP_ADD_MEMBERSHIP failed: %s", strerror(errno));
715         }
716     }
717 }
718
719 static void applyMulticastToInterface6(uint32_t interface)
720 {
721     if (!caglobals.ip.ipv6enabled)
722     {
723         return;
724     }
725     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressInt, interface);
726     applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressLnk, interface);
727     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressRlm, interface);
728     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressAdm, interface);
729     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressSit, interface);
730     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressOrg, interface);
731     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressGlb, interface);
732
733     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressInt, interface);
734     applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressLnk, interface);
735     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressRlm, interface);
736     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressAdm, interface);
737     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressSit, interface);
738     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressOrg, interface);
739     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressGlb, interface);
740 }
741
742 CAResult_t CAIPStartListenServer()
743 {
744     u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
745     if (!iflist)
746     {
747         OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
748         return CA_STATUS_FAILED;
749     }
750
751     uint32_t len = u_arraylist_length(iflist);
752     OIC_LOG_V(DEBUG, TAG, "IP network interfaces found: %d", len);
753
754     for (uint32_t i = 0; i < len; i++)
755     {
756         CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
757
758         if (!ifitem)
759         {
760             continue;
761         }
762         if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
763         {
764             continue;
765         }
766         if (ifitem->family == AF_INET)
767         {
768             struct in_addr inaddr;
769             inaddr.s_addr = ifitem->ipv4addr;
770             applyMulticastToInterface4(inaddr);
771             OIC_LOG_V(DEBUG, TAG, "IPv4 network interface: %s", ifitem->name);
772         }
773         if (ifitem->family == AF_INET6)
774         {
775             applyMulticastToInterface6(ifitem->index);
776             OIC_LOG_V(DEBUG, TAG, "IPv6 network interface: %s", ifitem->name);
777         }
778     }
779
780     u_arraylist_destroy(iflist);
781     return CA_STATUS_OK;
782 }
783
784 CAResult_t CAIPStopListenServer()
785 {
786     u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
787     if (!iflist)
788     {
789         OIC_LOG_V(ERROR, TAG, "Get interface info failed: %s", strerror(errno));
790         return CA_STATUS_FAILED;
791     }
792
793     uint32_t len = u_arraylist_length(iflist);
794     OIC_LOG_V(DEBUG, TAG, "IP network interfaces found: %d", len);
795
796     for (uint32_t i = 0; i < len; i++)
797     {
798         CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
799
800         if (!ifitem)
801         {
802             continue;
803         }
804
805         if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
806         {
807             continue;
808         }
809         if (ifitem->family == AF_INET)
810         {
811             close(caglobals.ip.m4.fd);
812             close(caglobals.ip.m4s.fd);
813             caglobals.ip.m4.fd = -1;
814             caglobals.ip.m4s.fd = -1;
815             OIC_LOG_V(DEBUG, TAG, "IPv4 network interface: %s cloed", ifitem->name);
816         }
817         if (ifitem->family == AF_INET6)
818         {
819             close(caglobals.ip.m6.fd);
820             close(caglobals.ip.m6s.fd);
821             caglobals.ip.m6.fd = -1;
822             caglobals.ip.m6s.fd = -1;
823             OIC_LOG_V(DEBUG, TAG, "IPv6 network interface: %s", ifitem->name);
824         }
825     }
826     u_arraylist_destroy(iflist);
827     return CA_STATUS_OK;
828 }
829
830 static void CAProcessNewInterface(CAInterface_t *ifitem)
831 {
832     if (!ifitem)
833     {
834         OIC_LOG(DEBUG, TAG, "ifitem is null");
835         return;
836     }
837     if (ifitem->family == AF_INET6)
838     {
839         applyMulticastToInterface6(ifitem->index);
840     }
841     if (ifitem->family == AF_INET)
842     {
843         struct in_addr inaddr = { .s_addr = ifitem->ipv4addr };
844         applyMulticastToInterface4(inaddr);
845     }
846 }
847 static void CAHandleNetlink()
848 {
849 }
850
851 void CAIPSetPacketReceiveCallback(CAIPPacketReceivedCallback callback)
852 {
853     g_packetReceivedCallback = callback;
854 }
855
856 void CAIPSetExceptionCallback(CAIPExceptionCallback callback)
857 {
858     g_exceptionCallback = callback;
859 }
860
861 void CAIPSetConnectionStateChangeCallback(CAIPConnectionStateChangeCallback callback)
862 {
863     CAIPSetNetworkMonitorCallback(callback);
864 }
865
866 static void sendData(int fd, const CAEndpoint_t *endpoint,
867                      const void *data, uint32_t dlen,
868                      const char *cast, const char *fam)
869 {
870     OIC_LOG(DEBUG, TAG, "IN");
871
872     if (!endpoint)
873     {
874         OIC_LOG(DEBUG, TAG, "endpoint is null");
875         return;
876     }
877
878     char *secure = (endpoint->flags & CA_SECURE) ? "secure " : "";
879     (void)secure;   // eliminates release warning
880     struct sockaddr_storage sock;
881     CAConvertNameToAddr(endpoint->addr, endpoint->port, &sock);
882
883     socklen_t socklen;
884     if (sock.ss_family == AF_INET6)
885     {
886         struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sock;
887         if (!sock6->sin6_scope_id)
888         {
889             sock6->sin6_scope_id = endpoint->interface;
890         }
891         socklen = sizeof(struct sockaddr_in6);
892     }
893     else
894     {
895         socklen = sizeof(struct sockaddr_in);
896     }
897
898     ssize_t len = sendto(fd, data, dlen, 0, (struct sockaddr *)&sock, socklen);
899     if (-1 == len)
900     {
901          // If logging is not defined/enabled.
902         (void)cast;
903         (void)fam;
904         OIC_LOG_V(ERROR, TAG, "%s%s %s sendTo failed: %s", secure, cast, fam, strerror(errno));
905     }
906     else
907     {
908         OIC_LOG_V(INFO, TAG, "%s%s %s sendTo is successful: %zd bytes", secure, cast, fam, len);
909     }
910 }
911
912 static void sendMulticastData6(const u_arraylist_t *iflist,
913                                CAEndpoint_t *endpoint,
914                                const void *data, uint32_t datalen)
915 {
916     if (!endpoint)
917     {
918         OIC_LOG(DEBUG, TAG, "endpoint is null");
919         return;
920     }
921
922     int scope = endpoint->flags & CA_SCOPE_MASK;
923     char *ipv6mcname = ipv6mcnames[scope];
924     if (!ipv6mcname)
925     {
926         OIC_LOG_V(INFO, TAG, "IPv6 multicast scope invalid: %d", scope);
927         return;
928     }
929     OICStrcpy(endpoint->addr, sizeof(endpoint->addr), ipv6mcname);
930     int fd = caglobals.ip.u6.fd;
931
932     uint32_t len = u_arraylist_length(iflist);
933     for (uint32_t i = 0; i < len; i++)
934     {
935         CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
936         if (!ifitem)
937         {
938             continue;
939         }
940         if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
941         {
942             continue;
943         }
944         if (ifitem->family != AF_INET6)
945         {
946             continue;
947         }
948
949         int index = ifitem->index;
950         if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, &index, sizeof (index)))
951         {
952             OIC_LOG_V(ERROR, TAG, "setsockopt6 failed: %s", strerror(errno));
953             return;
954         }
955         sendData(fd, endpoint, data, datalen, "multicast", "ipv6");
956     }
957 }
958
959 static void sendMulticastData4(const u_arraylist_t *iflist,
960                                CAEndpoint_t *endpoint,
961                                const void *data, uint32_t datalen)
962 {
963     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
964
965     struct ip_mreqn mreq = { .imr_multiaddr = IPv4MulticastAddress,
966                              .imr_ifindex = 0 };
967     OICStrcpy(endpoint->addr, sizeof(endpoint->addr), IPv4_MULTICAST);
968     int fd = caglobals.ip.u4.fd;
969
970     uint32_t len = u_arraylist_length(iflist);
971     for (uint32_t i = 0; i < len; i++)
972     {
973         CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
974         if (!ifitem)
975         {
976             continue;
977         }
978         if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
979         {
980             continue;
981         }
982         if (ifitem->family != AF_INET)
983         {
984             continue;
985         }
986
987         struct in_addr inaddr;
988         inaddr.s_addr = ifitem->ipv4addr;
989         mreq.imr_address = inaddr;
990         if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, &mreq, sizeof (mreq)))
991         {
992             OIC_LOG_V(ERROR, TAG, "send IP_MULTICAST_IF failed: %s (using defualt)",
993                     strerror(errno));
994         }
995         sendData(fd, endpoint, data, datalen, "multicast", "ipv4");
996     }
997 }
998
999 void CAIPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
1000                   bool isMulticast)
1001 {
1002     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
1003     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
1004
1005     bool isSecure = (endpoint->flags & CA_SECURE) != 0;
1006
1007     if (isMulticast)
1008     {
1009         endpoint->port = isSecure ? CA_SECURE_COAP : CA_COAP;
1010
1011         u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
1012         if (!iflist)
1013         {
1014             OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
1015             return;
1016         }
1017
1018         if ((endpoint->flags & CA_IPV6) && caglobals.ip.ipv6enabled)
1019         {
1020             sendMulticastData6(iflist, endpoint, data, datalen);
1021         }
1022         if ((endpoint->flags & CA_IPV4) && caglobals.ip.ipv4enabled)
1023         {
1024             sendMulticastData4(iflist, endpoint, data, datalen);
1025         }
1026
1027         u_arraylist_destroy(iflist);
1028     }
1029     else
1030     {
1031         if (!endpoint->port)    // unicast discovery
1032         {
1033             endpoint->port = isSecure ? CA_SECURE_COAP : CA_COAP;
1034         }
1035
1036         int fd;
1037         if (caglobals.ip.ipv6enabled && (endpoint->flags & CA_IPV6))
1038         {
1039             fd = isSecure ? caglobals.ip.u6s.fd : caglobals.ip.u6.fd;
1040 #ifndef __WITH_DTLS__
1041             fd = caglobals.ip.u6.fd;
1042 #endif
1043             sendData(fd, endpoint, data, datalen, "unicast", "ipv6");
1044         }
1045         if (caglobals.ip.ipv4enabled && (endpoint->flags & CA_IPV4))
1046         {
1047             fd = isSecure ? caglobals.ip.u4s.fd : caglobals.ip.u4.fd;
1048 #ifndef __WITH_DTLS__
1049             fd = caglobals.ip.u4.fd;
1050 #endif
1051             sendData(fd, endpoint, data, datalen, "unicast", "ipv4");
1052         }
1053     }
1054 }
1055
1056 CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1057 {
1058     VERIFY_NON_NULL(info, TAG, "info is NULL");
1059     VERIFY_NON_NULL(size, TAG, "size is NULL");
1060
1061     u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
1062     if (!iflist)
1063     {
1064         OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
1065         return CA_STATUS_FAILED;
1066     }
1067
1068     uint32_t len = u_arraylist_length(iflist);
1069     uint32_t length = len;
1070
1071 #ifdef __WITH_DTLS__
1072     //If DTLS is supported, each interface can support secure port as well
1073     length = len * 2;
1074 #endif
1075
1076     CAEndpoint_t *eps = (CAEndpoint_t *)OICCalloc(length, sizeof (CAEndpoint_t));
1077     if (!eps)
1078     {
1079         OIC_LOG(ERROR, TAG, "Malloc Failed");
1080         u_arraylist_destroy(iflist);
1081         return CA_MEMORY_ALLOC_FAILED;
1082     }
1083
1084     for (uint32_t i = 0, j = 0; i < len; i++)
1085     {
1086         CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1087         if(!ifitem)
1088         {
1089             continue;
1090         }
1091
1092         eps[j].adapter = CA_ADAPTER_IP;
1093         eps[j].interface = 0;
1094
1095         if (ifitem->family == AF_INET6)
1096         {
1097             eps[j].flags = CA_IPV6;
1098             eps[j].port = caglobals.ip.u6.port;
1099         }
1100         else
1101         {
1102             eps[j].flags = CA_IPV4;
1103             eps[j].port = caglobals.ip.u4.port;
1104
1105             inet_ntop(AF_INET, &(ifitem->ipv4addr), eps[j].addr, MAX_ADDR_STR_SIZE_CA);
1106         }
1107
1108 #ifdef __WITH_DTLS__
1109         j++;
1110
1111         eps[j].adapter = CA_ADAPTER_IP;
1112         eps[j].interface = 0;
1113
1114         if (ifitem->family == AF_INET6)
1115         {
1116             eps[j].flags = CA_IPV6 | CA_SECURE;
1117             eps[j].port = caglobals.ip.u6s.port;
1118         }
1119         else
1120         {
1121             eps[j].flags = CA_IPV4 | CA_SECURE;
1122             eps[j].port = caglobals.ip.u4s.port;
1123             inet_ntop(AF_INET, &(ifitem->ipv4addr), eps[j].addr, MAX_ADDR_STR_SIZE_CA);
1124         }
1125 #endif
1126         j++;
1127     }
1128
1129     *info = eps;
1130     *size = len;
1131
1132     u_arraylist_destroy(iflist);
1133
1134     return CA_STATUS_OK;
1135 }