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