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