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