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