merge master code to build iotivity
[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 CAApplyInterfaces();
100 static void CAFindReadyMessage();
101 static void CASelectReturned(fd_set *readFds, int ret);
102 static void CAProcessNewInterface(CAInterface_t *ifchanged);
103 static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags);
104
105 #define SET(TYPE, FDS) \
106     if (caglobals.ip.TYPE.fd != -1) \
107     { \
108         FD_SET(caglobals.ip.TYPE.fd, FDS); \
109     }
110
111 #define ISSET(TYPE, FDS, FLAGS) \
112     if (caglobals.ip.TYPE.fd != -1 && FD_ISSET(caglobals.ip.TYPE.fd, FDS)) \
113     { \
114         fd = caglobals.ip.TYPE.fd; \
115         flags = FLAGS; \
116     }
117
118 static void CAReceiveHandler(void *data)
119 {
120     (void)data;
121     OIC_LOG(DEBUG, TAG, "IN");
122
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
199         {
200             CAInterface_t *ifchanged = CAFindInterfaceChange();
201             if (ifchanged)
202             {
203                 CAProcessNewInterface(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,
463                              caglobals.ip.u4.fd, caglobals.ip.u4s.fd,
464                              caglobals.ip.m6.fd, caglobals.ip.m6s.fd,
465                              caglobals.ip.m4.fd, caglobals.ip.m4s.fd);
466
467     // create pipe for fast shutdown
468     CAInitializePipe();
469     CHECKFD(caglobals.ip.shutdownFds[0]);
470     CHECKFD(caglobals.ip.shutdownFds[1]);
471
472     // create source of network interface change notifications
473     CAInitializeNetlink();
474
475     caglobals.ip.selectTimeout = CAGetPollingInterval(caglobals.ip.selectTimeout);
476
477     CAApplyInterfaces();
478
479     caglobals.ip.terminate = false;
480     res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
481     if (CA_STATUS_OK != res)
482     {
483         OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
484         return res;
485     }
486     OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
487
488     caglobals.ip.started = true;
489     return CA_STATUS_OK;
490 }
491
492 void CAIPStopServer()
493 {
494     OIC_LOG(DEBUG, TAG, "IN");
495
496     caglobals.ip.terminate = true;
497
498     if (caglobals.ip.shutdownFds[1] != -1)
499     {
500         close(caglobals.ip.shutdownFds[1]);
501         // receive thread will stop immediately
502     }
503     else
504     {
505         // receive thread will stop in SELECT_TIMEOUT seconds.
506     }
507
508     OIC_LOG(DEBUG, TAG, "OUT");
509 }
510
511 void CAWakeUpForChange()
512 {
513     if (caglobals.ip.shutdownFds[1] != -1)
514     {
515         ssize_t len = 0;
516         do
517         {
518             len = write(caglobals.ip.shutdownFds[1], "w", 1);
519         } while ((len == -1) && (errno == EINTR));
520         if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
521         {
522             OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
523         }
524     }
525 }
526
527 static void applyMulticastToInterface4(struct in_addr inaddr)
528 {
529     if (!caglobals.ip.ipv4enabled)
530     {
531         return;
532     }
533
534     struct ip_mreq mreq = { .imr_multiaddr = IPv4MulticastAddress,
535                             .imr_interface = inaddr};
536     if (setsockopt(caglobals.ip.m4.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof (mreq)))
537     {
538         if (EADDRINUSE != errno)
539         {
540             OIC_LOG_V(ERROR, TAG, "IPv4 IP_ADD_MEMBERSHIP failed: %s", strerror(errno));
541         }
542     }
543     if (setsockopt(caglobals.ip.m4s.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof (mreq)))
544     {
545         if (EADDRINUSE != errno)
546         {
547             OIC_LOG_V(ERROR, TAG, "secure IPv4 IP_ADD_MEMBERSHIP failed: %s", strerror(errno));
548         }
549     }
550 }
551
552 static void applyMulticast6(int fd, struct in6_addr *addr, uint32_t interface)
553 {
554     struct ipv6_mreq mreq;
555     mreq.ipv6mr_multiaddr = *addr;
556     mreq.ipv6mr_interface = interface;
557     if (setsockopt(fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq, sizeof (mreq)))
558     {
559         if (EADDRINUSE != errno)
560         {
561             OIC_LOG_V(ERROR, TAG, "IPv6 IP_ADD_MEMBERSHIP failed: %s", strerror(errno));
562         }
563     }
564 }
565
566 static void applyMulticastToInterface6(uint32_t interface)
567 {
568     if (!caglobals.ip.ipv6enabled)
569     {
570         return;
571     }
572     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressInt, interface);
573     applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressLnk, interface);
574     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressRlm, interface);
575     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressAdm, interface);
576     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressSit, interface);
577     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressOrg, interface);
578     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressGlb, interface);
579     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressInt, interface);
580     applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressLnk, interface);
581     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressRlm, interface);
582     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressAdm, interface);
583     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressSit, interface);
584     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressOrg, interface);
585     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressGlb, interface);
586 }
587
588 static void CAApplyInterfaces()
589 {
590     u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
591     if (!iflist)
592     {
593         OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
594         return;
595     }
596
597     uint32_t len = u_arraylist_length(iflist);
598     OIC_LOG_V(DEBUG, TAG, "IP network interfaces found: %d", len);
599
600     for (uint32_t i = 0; i < len; i++)
601     {
602         CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
603
604         if (!ifitem)
605         {
606             continue;
607         }
608         if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
609         {
610             continue;
611         }
612         if (ifitem->family == AF_INET)
613         {
614             struct in_addr inaddr;
615             inaddr.s_addr = ifitem->ipv4addr;
616             applyMulticastToInterface4(inaddr);
617             OIC_LOG_V(DEBUG, TAG, "IPv4 network interface: %s", ifitem->name);
618         }
619         if (ifitem->family == AF_INET6)
620         {
621             applyMulticastToInterface6(ifitem->index);
622             OIC_LOG_V(DEBUG, TAG, "IPv6 network interface: %s", ifitem->name);
623         }
624     }
625
626     u_arraylist_destroy(iflist);
627 }
628
629 static void CAProcessNewInterface(CAInterface_t *ifitem)
630 {
631     applyMulticastToInterface6(ifitem->index);
632     struct in_addr inaddr;
633     inaddr.s_addr = ifitem->ipv4addr;
634     applyMulticastToInterface4(inaddr);
635 }
636 static void CAHandleNetlink()
637 {
638 #ifdef __linux__
639     char buf[4096];
640     struct nlmsghdr *nh;
641     struct sockaddr_nl sa;
642     struct iovec iov = { buf, sizeof (buf) };
643     struct msghdr msg = { (void *)&sa, sizeof (sa), &iov, 1, NULL, 0, 0 };
644
645     size_t len = recvmsg(caglobals.ip.netlinkFd, &msg, 0);
646
647     for (nh = (struct nlmsghdr *)buf; NLMSG_OK(nh, len); nh = NLMSG_NEXT(nh, len))
648     {
649         if (nh->nlmsg_type != RTM_NEWLINK)
650         {
651             continue;
652         }
653
654         struct ifinfomsg *ifi = (struct ifinfomsg *)NLMSG_DATA(nh);
655         if (!ifi || (ifi->ifi_flags & IFF_LOOPBACK) || !(ifi->ifi_flags & IFF_RUNNING))
656         {
657             continue;
658         }
659
660         int newIndex = ifi->ifi_index;
661
662         u_arraylist_t *iflist = CAIPGetInterfaceInformation(newIndex);
663         if (!iflist)
664         {
665             OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
666             return;
667         }
668
669         uint32_t listLength = u_arraylist_length(iflist);
670         for (uint32_t i = 0; i < listLength; i++)
671         {
672             CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
673             if (!ifitem)
674             {
675                 continue;
676             }
677
678             if ((int)ifitem->index != newIndex)
679             {
680                 continue;
681             }
682
683             CAProcessNewInterface(ifitem);
684             break; // we found the one we were looking for
685         }
686         u_arraylist_destroy(iflist);
687     }
688 #endif // __linux__
689 }
690
691 void CAIPSetPacketReceiveCallback(CAIPPacketReceivedCallback callback)
692 {
693     OIC_LOG(DEBUG, TAG, "IN");
694
695     g_packetReceivedCallback = callback;
696
697     OIC_LOG(DEBUG, TAG, "OUT");
698 }
699
700 void CAIPSetExceptionCallback(CAIPExceptionCallback callback)
701 {
702     OIC_LOG(DEBUG, TAG, "IN");
703
704     g_exceptionCallback = callback;
705
706     OIC_LOG(DEBUG, TAG, "OUT");
707 }
708
709 static void sendData(int fd, const CAEndpoint_t *endpoint,
710                      const void *data, uint32_t dlen,
711                      const char *cast, const char *fam)
712 {
713     OIC_LOG(DEBUG, TAG, "IN");
714
715     char *secure = (endpoint->flags & CA_SECURE) ? "secure " : "";
716     (void)secure;   // eliminates release warning
717     struct sockaddr_storage sock;
718     CAConvertNameToAddr(endpoint->addr, endpoint->port, &sock);
719
720     socklen_t socklen;
721     if (sock.ss_family == AF_INET6)
722     {
723         struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sock;
724         if (!sock6->sin6_scope_id)
725         {
726             sock6->sin6_scope_id = endpoint->interface;
727         }
728         socklen = sizeof(struct sockaddr_in6);
729     }
730     else
731     {
732         socklen = sizeof(struct sockaddr_in);
733     }
734
735     ssize_t len = sendto(fd, data, dlen, 0, (struct sockaddr *)&sock, socklen);
736     if (-1 == len)
737     {
738          // If logging is not defined/enabled.
739         (void)cast;
740         (void)fam;
741         OIC_LOG_V(ERROR, TAG, "%s%s %s sendTo failed: %s", secure, cast, fam, strerror(errno));
742     }
743     else
744     {
745         OIC_LOG_V(INFO, TAG, "%s%s %s sendTo is successful: %d bytes", secure, cast, fam, len);
746     }
747 }
748
749 static void sendMulticastData6(const u_arraylist_t *iflist,
750                                CAEndpoint_t *endpoint,
751                                const void *data, uint32_t datalen)
752 {
753     int scope = endpoint->flags & CA_SCOPE_MASK;
754     char *ipv6mcname = ipv6mcnames[scope];
755     if (!ipv6mcname)
756     {
757         OIC_LOG_V(INFO, TAG, "IPv6 multicast scope invalid: %d", scope);
758         return;
759     }
760     OICStrcpy(endpoint->addr, sizeof(endpoint->addr), ipv6mcname);
761     int fd = caglobals.ip.u6.fd;
762
763     uint32_t len = u_arraylist_length(iflist);
764     for (uint32_t i = 0; i < len; i++)
765     {
766         CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
767         if (!ifitem)
768         {
769             continue;
770         }
771         if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
772         {
773             continue;
774         }
775         if (ifitem->family != AF_INET6)
776         {
777             continue;
778         }
779
780         int index = ifitem->index;
781         if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, &index, sizeof (index)))
782         {
783             OIC_LOG_V(ERROR, TAG, "setsockopt6 failed: %s", strerror(errno));
784             return;
785         }
786         sendData(fd, endpoint, data, datalen, "multicast", "ipv6");
787     }
788 }
789
790 static void sendMulticastData4(const u_arraylist_t *iflist,
791                                CAEndpoint_t *endpoint,
792                                const void *data, uint32_t datalen)
793 {
794     struct ip_mreq mreq = { .imr_multiaddr = IPv4MulticastAddress };
795     OICStrcpy(endpoint->addr, sizeof(endpoint->addr), IPv4_MULTICAST);
796     int fd = caglobals.ip.u4.fd;
797
798     uint32_t len = u_arraylist_length(iflist);
799     for (uint32_t i = 0; i < len; i++)
800     {
801         CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
802         if (!ifitem)
803         {
804             continue;
805         }
806         if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
807         {
808             continue;
809         }
810         if (ifitem->family != AF_INET)
811         {
812             continue;
813         }
814
815         struct in_addr inaddr;
816         inaddr.s_addr = ifitem->ipv4addr;
817         mreq.imr_interface = inaddr;
818         if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, &mreq, sizeof (mreq)))
819         {
820             OIC_LOG_V(ERROR, TAG, "send IP_MULTICAST_IF failed: %s (using defualt)",
821                     strerror(errno));
822         }
823         sendData(fd, endpoint, data, datalen, "multicast", "ipv4");
824     }
825 }
826
827 void CAIPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
828                                                             bool isMulticast)
829 {
830     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
831     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
832
833     bool isSecure = (endpoint->flags & CA_SECURE) != 0;
834
835     if (isMulticast)
836     {
837         endpoint->port = isSecure ? CA_SECURE_COAP : CA_COAP;
838
839         u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
840         if (!iflist)
841         {
842             OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
843             return;
844         }
845
846         if ((endpoint->flags & CA_IPV6) && caglobals.ip.ipv6enabled)
847         {
848             sendMulticastData6(iflist, endpoint, data, datalen);
849         }
850         if ((endpoint->flags & CA_IPV4) && caglobals.ip.ipv4enabled)
851         {
852             sendMulticastData4(iflist, endpoint, data, datalen);
853         }
854
855         u_arraylist_destroy(iflist);
856     }
857     else
858     {
859         if (!endpoint->port)    // unicast discovery
860         {
861             endpoint->port = isSecure ? CA_SECURE_COAP : CA_COAP;
862         }
863
864         int fd;
865         if (caglobals.ip.ipv6enabled && (endpoint->flags & CA_IPV6))
866         {
867             fd = isSecure ? caglobals.ip.u6s.fd : caglobals.ip.u6.fd;
868             #ifndef __WITH_DTLS__
869             fd = caglobals.ip.u6.fd;
870             #endif
871             sendData(fd, endpoint, data, datalen, "unicast", "ipv6");
872         }
873         if (caglobals.ip.ipv4enabled && (endpoint->flags & CA_IPV4))
874         {
875             fd = isSecure ? caglobals.ip.u4s.fd : caglobals.ip.u4.fd;
876             #ifndef __WITH_DTLS__
877             fd = caglobals.ip.u4.fd;
878             #endif
879             sendData(fd, endpoint, data, datalen, "unicast", "ipv4");
880         }
881     }
882 }
883
884 CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
885 {
886     OIC_LOG(DEBUG, TAG, "IN");
887
888     VERIFY_NON_NULL(info, TAG, "info is NULL");
889     VERIFY_NON_NULL(size, TAG, "size is NULL");
890
891     u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
892     if (!iflist)
893     {
894         OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
895         return CA_STATUS_FAILED;
896     }
897
898     uint32_t len = u_arraylist_length(iflist);
899
900     CAEndpoint_t *eps = (CAEndpoint_t *)OICCalloc(len, sizeof (CAEndpoint_t));
901     if (!eps)
902     {
903         OIC_LOG(ERROR, TAG, "Malloc Failed");
904         u_arraylist_destroy(iflist);
905         return CA_MEMORY_ALLOC_FAILED;
906     }
907
908     for (uint32_t i = 0, j = 0; i < len; i++)
909     {
910         CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
911         if(!ifitem)
912         {
913             continue;
914         }
915
916         OICStrcpy(eps[j].addr, CA_INTERFACE_NAME_SIZE, ifitem->name);
917         eps[j].flags = ifitem->family == AF_INET6 ? CA_IPV6 : CA_IPV4;
918         eps[j].adapter = CA_ADAPTER_IP;
919         eps[j].interface = 0;
920         eps[j].port = 0;
921         j++;
922     }
923
924     *info = eps;
925     *size = len;
926
927     u_arraylist_destroy(iflist);
928
929     OIC_LOG(DEBUG, TAG, "OUT");
930     return CA_STATUS_OK;
931 }
932