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