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