1 /*****************************************************************j
3 * Copyright 2014 Samsung Electronics All Rights Reserved.
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 ******************************************************************/
21 #ifndef __APPLE_USE_RFC_3542
22 #define __APPLE_USE_RFC_3542 // for PKTINFO
25 #define _GNU_SOURCE // for in6_pktinfo
28 #include <sys/types.h>
29 #include <sys/socket.h>
32 #include <sys/types.h>
34 #include <sys/select.h>
35 #include <arpa/inet.h>
36 #include <netinet/in.h>
40 #include <linux/netlink.h>
41 #include <linux/rtnetlink.h>
45 #include "caipinterface.h"
46 #include "caadapterutils.h"
48 #include "caadapternetdtls.h"
51 #include "oic_malloc.h"
52 #include "oic_string.h"
55 * Logging tag for module name
57 #define TAG "OIC_CA_IP_SERVER"
59 #define SELECT_TIMEOUT 1 // select() seconds (and termination latency)
61 #define IPv4_MULTICAST "224.0.1.187"
62 static struct in_addr IPv4MulticastAddress = { 0 };
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;
80 static char *ipv6mcnames[IPv6_DOMAINS] = {
99 static CAIPPacketReceivedCallback g_packetReceivedCallback = NULL;
101 static CAIPErrorHandleCallback g_ipErrorHandler = NULL;
103 static void CAFindReadyMessage();
104 static void CASelectReturned(fd_set *readFds, int ret);
105 static void CAProcessNewInterface(CAInterface_t *ifchanged);
106 static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags);
108 #define SET(TYPE, FDS) \
109 if (caglobals.ip.TYPE.fd != -1) \
111 FD_SET(caglobals.ip.TYPE.fd, FDS); \
114 #define ISSET(TYPE, FDS, FLAGS) \
115 if (caglobals.ip.TYPE.fd != -1 && FD_ISSET(caglobals.ip.TYPE.fd, FDS)) \
117 fd = caglobals.ip.TYPE.fd; \
121 #define CLOSE_SOCKET(TYPE) \
122 if (caglobals.ip.TYPE.fd != -1) \
124 close(caglobals.ip.TYPE.fd); \
125 caglobals.ip.TYPE.fd = -1; \
128 void CADeInitializeIPGlobals()
139 if (caglobals.ip.netlinkFd != -1)
141 close(caglobals.ip.netlinkFd);
142 caglobals.ip.netlinkFd = -1;
146 static void CAReceiveHandler(void *data)
150 while (!caglobals.ip.terminate)
152 CAFindReadyMessage();
156 static void CAFindReadyMessage()
159 struct timeval timeout;
161 timeout.tv_sec = caglobals.ip.selectTimeout;
163 struct timeval *tv = caglobals.ip.selectTimeout == -1 ? NULL : &timeout;
174 if (caglobals.ip.shutdownFds[0] != -1)
176 FD_SET(caglobals.ip.shutdownFds[0], &readFds);
178 if (caglobals.ip.netlinkFd != -1)
180 FD_SET(caglobals.ip.netlinkFd, &readFds);
183 int ret = select(caglobals.ip.maxfd + 1, &readFds, NULL, NULL, tv);
185 if (caglobals.ip.terminate)
187 OIC_LOG_V(DEBUG, TAG, "Packet receiver Stop request received.");
194 OIC_LOG_V(FATAL, TAG, "select error %s", strerror(errno));
199 CASelectReturned(&readFds, ret);
202 static void CASelectReturned(fd_set *readFds, int ret)
206 CATransportFlags_t flags = CA_DEFAULT_FLAGS;
208 while (!caglobals.ip.terminate)
210 ISSET(u6, readFds, CA_IPV6)
211 else ISSET(u6s, readFds, CA_IPV6 | CA_SECURE)
212 else ISSET(u4, readFds, CA_IPV4)
213 else ISSET(u4s, readFds, CA_IPV4 | CA_SECURE)
214 else ISSET(m6, readFds, CA_MULTICAST | CA_IPV6)
215 else ISSET(m6s, readFds, CA_MULTICAST | CA_IPV6 | CA_SECURE)
216 else ISSET(m4, readFds, CA_MULTICAST | CA_IPV4)
217 else ISSET(m4s, readFds, CA_MULTICAST | CA_IPV4 | CA_SECURE)
218 else if (FD_ISSET(caglobals.ip.netlinkFd, readFds))
220 CAInterface_t *ifchanged = CAFindInterfaceChange();
223 CAProcessNewInterface(ifchanged);
228 else if (FD_ISSET(caglobals.ip.shutdownFds[0], readFds))
231 ssize_t len = read(caglobals.ip.shutdownFds[0], buf, sizeof (buf));
243 (void)CAReceiveMessage(fd, flags);
248 static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags)
250 char recvBuffer[COAP_MAX_PDU_SIZE] = {0};
253 int level, type, namelen;
254 struct sockaddr_storage srcAddr;
255 unsigned char *pktinfo = NULL;
256 struct cmsghdr *cmp = NULL;
257 struct iovec iov = { recvBuffer, sizeof (recvBuffer) };
261 unsigned char data[CMSG_SPACE(sizeof (struct in6_pktinfo))];
266 namelen = sizeof (struct sockaddr_in6);
267 level = IPPROTO_IPV6;
269 len = sizeof (struct in6_pktinfo);
273 namelen = sizeof (struct sockaddr_in);
276 len = sizeof (struct in6_pktinfo);
279 struct msghdr msg = { .msg_name = &srcAddr,
280 .msg_namelen = namelen,
283 .msg_control = &cmsg,
284 .msg_controllen = CMSG_SPACE(len) };
286 ssize_t recvLen = recvmsg(fd, &msg, flags);
289 OIC_LOG_V(ERROR, TAG, "Recvfrom failed %s", strerror(errno));
290 return CA_STATUS_FAILED;
293 if (flags & CA_MULTICAST)
295 for (cmp = CMSG_FIRSTHDR(&msg); cmp != NULL; cmp = CMSG_NXTHDR(&msg, cmp))
297 if (cmp->cmsg_level == level && cmp->cmsg_type == type)
299 pktinfo = CMSG_DATA(cmp);
304 CASecureEndpoint_t sep = {.endpoint = {.adapter = CA_ADAPTER_IP, .flags = flags}};
308 sep.endpoint.interface = ((struct sockaddr_in6 *)&srcAddr)->sin6_scope_id;
309 ((struct sockaddr_in6 *)&srcAddr)->sin6_scope_id = 0;
311 if ((flags & CA_MULTICAST) && pktinfo)
313 struct in6_addr *addr = &(((struct in6_pktinfo *)pktinfo)->ipi6_addr);
314 unsigned char topbits = ((unsigned char *)addr)[0];
317 sep.endpoint.flags &= ~CA_MULTICAST;
323 if ((flags & CA_MULTICAST) && pktinfo)
325 struct in_addr *addr = &((struct in_pktinfo *)pktinfo)->ipi_addr;
326 uint32_t host = ntohl(addr->s_addr);
327 unsigned char topbits = ((unsigned char *)&host)[3];
328 if (topbits < 224 || topbits > 239)
330 sep.endpoint.flags &= ~CA_MULTICAST;
335 CAConvertAddrToName(&srcAddr, msg.msg_namelen, sep.endpoint.addr, &sep.endpoint.port);
337 if (flags & CA_SECURE)
340 int ret = CAAdapterNetDtlsDecrypt(&sep, (uint8_t *)recvBuffer, recvLen);
341 OIC_LOG_V(DEBUG, TAG, "CAAdapterNetDtlsDecrypt returns [%d]", ret);
343 OIC_LOG(ERROR, TAG, "Encrypted message but no DTLS");
348 if (g_packetReceivedCallback)
350 g_packetReceivedCallback(&sep, recvBuffer, recvLen);
359 OIC_LOG(DEBUG, TAG, "IN");
360 OIC_LOG(DEBUG, TAG, "OUT");
363 static int CACreateSocket(int family, uint16_t *port, bool isMulticast)
365 int socktype = SOCK_DGRAM;
367 socktype |= SOCK_CLOEXEC;
369 int fd = socket(family, socktype, IPPROTO_UDP);
372 OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
377 int fl = fcntl(fd, F_GETFD);
378 if (-1 == fl || -1 == fcntl(fd, F_SETFD, fl|FD_CLOEXEC))
380 OIC_LOG_V(ERROR, TAG, "set FD_CLOEXEC failed: %s", strerror(errno));
386 struct sockaddr_storage sa = { .ss_family = family };
389 if (family == AF_INET6)
393 if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
395 OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
398 if (isMulticast && *port) // only do this for multicast ports
400 if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof (on)))
402 OIC_LOG_V(ERROR, TAG, "IPV6_RECVPKTINFO failed: %s", strerror(errno));
406 ((struct sockaddr_in6 *)&sa)->sin6_port = htons(*port);
407 socklen = sizeof (struct sockaddr_in6);
411 if (isMulticast && *port) // only do this for multicast ports
414 if (-1 == setsockopt(fd, IPPROTO_IP, IP_PKTINFO, &on, sizeof (on)))
416 OIC_LOG_V(ERROR, TAG, "IP_PKTINFO failed: %s", strerror(errno));
420 ((struct sockaddr_in *)&sa)->sin_port = htons(*port);
421 socklen = sizeof (struct sockaddr_in);
424 if (isMulticast && *port) // use the given port
427 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof (on)))
429 OIC_LOG_V(ERROR, TAG, "SO_REUSEADDR failed: %s", strerror(errno));
435 if (-1 == bind(fd, (struct sockaddr *)&sa, socklen))
437 OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
442 if (!*port) // return the assigned port
444 if (-1 == getsockname(fd, (struct sockaddr *)&sa, &socklen))
446 OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
450 *port = ntohs(family == AF_INET6 ?
451 ((struct sockaddr_in6 *)&sa)->sin6_port :
452 ((struct sockaddr_in *)&sa)->sin_port);
458 #define CHECKFD(FD) \
459 if (FD > caglobals.ip.maxfd) \
460 caglobals.ip.maxfd = FD;
461 #define NEWSOCKET(FAMILY, NAME, MULTICAST) \
462 caglobals.ip.NAME.fd = CACreateSocket(FAMILY, &caglobals.ip.NAME.port, MULTICAST); \
463 if (caglobals.ip.NAME.fd == -1) \
465 caglobals.ip.NAME.port = 0; \
466 caglobals.ip.NAME.fd = CACreateSocket(FAMILY, &caglobals.ip.NAME.port, MULTICAST); \
468 CHECKFD(caglobals.ip.NAME.fd)
470 static void CAInitializeNetlink()
473 // create NETLINK fd for interface change notifications
474 struct sockaddr_nl sa = { AF_NETLINK, 0, 0, RTMGRP_LINK };
476 caglobals.ip.netlinkFd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC, NETLINK_ROUTE);
477 if (caglobals.ip.netlinkFd == -1)
479 OIC_LOG_V(ERROR, TAG, "netlink socket failed: %s", strerror(errno));
483 int r = bind(caglobals.ip.netlinkFd, (struct sockaddr *)&sa, sizeof (sa));
486 OIC_LOG_V(ERROR, TAG, "netlink bind failed: %s", strerror(errno));
487 close(caglobals.ip.netlinkFd);
488 caglobals.ip.netlinkFd = -1;
492 CHECKFD(caglobals.ip.netlinkFd);
498 static void CAInitializePipe()
500 caglobals.ip.selectTimeout = -1;
502 int ret = pipe2(caglobals.ip.shutdownFds, O_CLOEXEC);
504 int ret = pipe(caglobals.ip.shutdownFds);
507 ret = fcntl(caglobals.ip.shutdownFds[0], F_GETFD);
510 ret = fcntl(caglobals.ip.shutdownFds[0], F_SETFD, ret|FD_CLOEXEC);
514 ret = fcntl(caglobals.ip.shutdownFds[1], F_GETFD);
518 ret = fcntl(caglobals.ip.shutdownFds[1], F_SETFD, ret|FD_CLOEXEC);
522 close(caglobals.ip.shutdownFds[1]);
523 close(caglobals.ip.shutdownFds[0]);
524 caglobals.ip.shutdownFds[0] = -1;
525 caglobals.ip.shutdownFds[1] = -1;
531 OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
532 caglobals.ip.selectTimeout = SELECT_TIMEOUT; //poll needed for shutdown
536 CAResult_t CAIPStartServer(const ca_thread_pool_t threadPool)
538 CAResult_t res = CA_STATUS_OK;
540 if (caglobals.ip.started)
545 if (!IPv4MulticastAddress.s_addr)
547 (void)inet_pton(AF_INET, IPv4_MULTICAST, &IPv4MulticastAddress);
548 (void)inet_pton(AF_INET6, IPv6_MULTICAST_INT, &IPv6MulticastAddressInt);
549 (void)inet_pton(AF_INET6, IPv6_MULTICAST_LNK, &IPv6MulticastAddressLnk);
550 (void)inet_pton(AF_INET6, IPv6_MULTICAST_RLM, &IPv6MulticastAddressRlm);
551 (void)inet_pton(AF_INET6, IPv6_MULTICAST_ADM, &IPv6MulticastAddressAdm);
552 (void)inet_pton(AF_INET6, IPv6_MULTICAST_SIT, &IPv6MulticastAddressSit);
553 (void)inet_pton(AF_INET6, IPv6_MULTICAST_ORG, &IPv6MulticastAddressOrg);
554 (void)inet_pton(AF_INET6, IPv6_MULTICAST_GLB, &IPv6MulticastAddressGlb);
557 if (!caglobals.ip.ipv6enabled && !caglobals.ip.ipv4enabled)
559 caglobals.ip.ipv4enabled = true; // only needed to run CA tests
562 if (caglobals.ip.ipv6enabled)
564 NEWSOCKET(AF_INET6, u6, false)
565 NEWSOCKET(AF_INET6, u6s, false)
566 NEWSOCKET(AF_INET6, m6, true)
567 NEWSOCKET(AF_INET6, m6s, true)
568 OIC_LOG_V(INFO, TAG, "IPv6 unicast port: %u", caglobals.ip.u6.port);
570 if (caglobals.ip.ipv4enabled)
572 NEWSOCKET(AF_INET, u4, false)
573 NEWSOCKET(AF_INET, u4s, false)
574 NEWSOCKET(AF_INET, m4, true)
575 NEWSOCKET(AF_INET, m4s, true)
576 OIC_LOG_V(INFO, TAG, "IPv4 unicast port: %u", caglobals.ip.u4.port);
579 OIC_LOG_V(DEBUG, TAG,
580 "socket summary: u6=%d, u6s=%d, u4=%d, u4s=%d, m6=%d, m6s=%d, m4=%d, m4s=%d",
581 caglobals.ip.u6.fd, caglobals.ip.u6s.fd, caglobals.ip.u4.fd, caglobals.ip.u4s.fd,
582 caglobals.ip.m6.fd, caglobals.ip.m6s.fd, caglobals.ip.m4.fd, caglobals.ip.m4s.fd);
584 OIC_LOG_V(DEBUG, TAG,
585 "port summary: u6 port=%d, u6s port=%d, u4 port=%d, u4s port=%d, m6 port=%d,"
586 "m6s port=%d, m4 port=%d, m4s port=%d",
587 caglobals.ip.u6.port, caglobals.ip.u6s.port, caglobals.ip.u4.port,
588 caglobals.ip.u4s.port, caglobals.ip.m6.port, caglobals.ip.m6s.port,
589 caglobals.ip.m4.port, caglobals.ip.m4s.port);
590 // create pipe for fast shutdown
592 CHECKFD(caglobals.ip.shutdownFds[0]);
593 CHECKFD(caglobals.ip.shutdownFds[1]);
595 // create source of network interface change notifications
596 CAInitializeNetlink();
598 caglobals.ip.selectTimeout = CAGetPollingInterval(caglobals.ip.selectTimeout);
600 res = CAIPStartListenServer();
601 if (CA_STATUS_OK != res)
603 OIC_LOG_V(ERROR, TAG, "Failed to start listening server![%d]", res);
607 caglobals.ip.terminate = false;
608 res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
609 if (CA_STATUS_OK != res)
611 OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
614 OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
616 caglobals.ip.started = true;
620 void CAIPStopServer()
622 caglobals.ip.started = false;
623 caglobals.ip.terminate = true;
625 if (caglobals.ip.shutdownFds[1] != -1)
627 close(caglobals.ip.shutdownFds[1]);
628 // receive thread will stop immediately
632 // receive thread will stop in SELECT_TIMEOUT seconds.
636 void CAWakeUpForChange()
638 if (caglobals.ip.shutdownFds[1] != -1)
643 len = write(caglobals.ip.shutdownFds[1], "w", 1);
644 } while ((len == -1) && (errno == EINTR));
645 if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
647 OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
652 static void applyMulticastToInterface4(struct in_addr inaddr)
654 if (!caglobals.ip.ipv4enabled)
659 struct ip_mreqn mreq = { .imr_multiaddr = IPv4MulticastAddress,
660 .imr_address = inaddr,
662 if (setsockopt(caglobals.ip.m4.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof (mreq)))
664 if (EADDRINUSE != errno)
666 OIC_LOG_V(ERROR, TAG, "IPv4 IP_ADD_MEMBERSHIP failed: %s", strerror(errno));
669 if (setsockopt(caglobals.ip.m4s.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof (mreq)))
671 if (EADDRINUSE != errno)
673 OIC_LOG_V(ERROR, TAG, "secure IPv4 IP_ADD_MEMBERSHIP failed: %s", strerror(errno));
678 static void applyMulticast6(int fd, struct in6_addr *addr, uint32_t interface)
680 struct ipv6_mreq mreq = {.ipv6mr_multiaddr = *addr, .ipv6mr_interface = interface};
682 if (setsockopt(fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq, sizeof (mreq)))
684 if (EADDRINUSE != errno)
686 OIC_LOG_V(ERROR, TAG, "IPv6 IP_ADD_MEMBERSHIP failed: %s", strerror(errno));
691 static void applyMulticastToInterface6(uint32_t interface)
693 if (!caglobals.ip.ipv6enabled)
697 //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressInt, interface);
698 applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressLnk, interface);
699 //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressRlm, interface);
700 //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressAdm, interface);
701 //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressSit, interface);
702 //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressOrg, interface);
703 //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressGlb, interface);
705 //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressInt, interface);
706 applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressLnk, interface);
707 //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressRlm, interface);
708 //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressAdm, interface);
709 //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressSit, interface);
710 //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressOrg, interface);
711 //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressGlb, interface);
714 CAResult_t CAIPStartListenServer()
716 u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
719 OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
720 return CA_STATUS_FAILED;
723 uint32_t len = u_arraylist_length(iflist);
724 OIC_LOG_V(DEBUG, TAG, "IP network interfaces found: %d", len);
726 for (uint32_t i = 0; i < len; i++)
728 CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
734 if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
738 if (ifitem->family == AF_INET)
740 struct in_addr inaddr;
741 inaddr.s_addr = ifitem->ipv4addr;
742 applyMulticastToInterface4(inaddr);
743 OIC_LOG_V(DEBUG, TAG, "IPv4 network interface: %s", ifitem->name);
745 if (ifitem->family == AF_INET6)
747 applyMulticastToInterface6(ifitem->index);
748 OIC_LOG_V(DEBUG, TAG, "IPv6 network interface: %s", ifitem->name);
752 u_arraylist_destroy(iflist);
756 CAResult_t CAIPStopListenServer()
758 u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
761 OIC_LOG_V(ERROR, TAG, "Get interface info failed: %s", strerror(errno));
762 return CA_STATUS_FAILED;
765 uint32_t len = u_arraylist_length(iflist);
766 OIC_LOG_V(DEBUG, TAG, "IP network interfaces found: %d", len);
768 for (uint32_t i = 0; i < len; i++)
770 CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
777 if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
781 if (ifitem->family == AF_INET)
783 close(caglobals.ip.m4.fd);
784 close(caglobals.ip.m4s.fd);
785 caglobals.ip.m4.fd = -1;
786 caglobals.ip.m4s.fd = -1;
787 OIC_LOG_V(DEBUG, TAG, "IPv4 network interface: %s cloed", ifitem->name);
789 if (ifitem->family == AF_INET6)
791 close(caglobals.ip.m6.fd);
792 close(caglobals.ip.m6s.fd);
793 caglobals.ip.m6.fd = -1;
794 caglobals.ip.m6s.fd = -1;
795 OIC_LOG_V(DEBUG, TAG, "IPv6 network interface: %s", ifitem->name);
798 u_arraylist_destroy(iflist);
802 static void CAProcessNewInterface(CAInterface_t *ifitem)
806 OIC_LOG(DEBUG, TAG, "ifitem is null");
809 if (ifitem->family == AF_INET6)
811 applyMulticastToInterface6(ifitem->index);
813 if (ifitem->family == AF_INET)
815 struct in_addr inaddr = { .s_addr = ifitem->ipv4addr };
816 applyMulticastToInterface4(inaddr);
820 void CAIPSetPacketReceiveCallback(CAIPPacketReceivedCallback callback)
822 g_packetReceivedCallback = callback;
825 void CAIPSetConnectionStateChangeCallback(CAIPConnectionStateChangeCallback callback)
827 CAIPSetNetworkMonitorCallback(callback);
830 static void sendData(int fd, const CAEndpoint_t *endpoint,
831 const void *data, uint32_t dlen,
832 const char *cast, const char *fam)
834 OIC_LOG(DEBUG, TAG, "IN");
838 OIC_LOG(DEBUG, TAG, "endpoint is null");
839 if (g_ipErrorHandler)
841 g_ipErrorHandler(endpoint, data, dlen, CA_STATUS_INVALID_PARAM);
846 char *secure = (endpoint->flags & CA_SECURE) ? "secure " : "";
847 (void)secure; // eliminates release warning
848 struct sockaddr_storage sock;
849 CAConvertNameToAddr(endpoint->addr, endpoint->port, &sock);
852 if (sock.ss_family == AF_INET6)
854 struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sock;
855 if (!sock6->sin6_scope_id)
857 sock6->sin6_scope_id = endpoint->interface;
859 socklen = sizeof(struct sockaddr_in6);
863 socklen = sizeof(struct sockaddr_in);
866 ssize_t len = sendto(fd, data, dlen, 0, (struct sockaddr *)&sock, socklen);
869 // If logging is not defined/enabled.
872 if (g_ipErrorHandler)
874 g_ipErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
876 OIC_LOG_V(ERROR, TAG, "%s%s %s sendTo failed: %s", secure, cast, fam, strerror(errno));
880 OIC_LOG_V(INFO, TAG, "%s%s %s sendTo is successful: %zd bytes", secure, cast, fam, len);
884 static void sendMulticastData6(const u_arraylist_t *iflist,
885 CAEndpoint_t *endpoint,
886 const void *data, uint32_t datalen)
890 OIC_LOG(DEBUG, TAG, "endpoint is null");
894 int scope = endpoint->flags & CA_SCOPE_MASK;
895 char *ipv6mcname = ipv6mcnames[scope];
898 OIC_LOG_V(INFO, TAG, "IPv6 multicast scope invalid: %d", scope);
901 OICStrcpy(endpoint->addr, sizeof(endpoint->addr), ipv6mcname);
902 int fd = caglobals.ip.u6.fd;
904 uint32_t len = u_arraylist_length(iflist);
905 for (uint32_t i = 0; i < len; i++)
907 CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
912 if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
916 if (ifitem->family != AF_INET6)
921 int index = ifitem->index;
922 if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, &index, sizeof (index)))
924 OIC_LOG_V(ERROR, TAG, "setsockopt6 failed: %s", strerror(errno));
927 sendData(fd, endpoint, data, datalen, "multicast", "ipv6");
931 static void sendMulticastData4(const u_arraylist_t *iflist,
932 CAEndpoint_t *endpoint,
933 const void *data, uint32_t datalen)
935 VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
937 struct ip_mreqn mreq = { .imr_multiaddr = IPv4MulticastAddress,
939 OICStrcpy(endpoint->addr, sizeof(endpoint->addr), IPv4_MULTICAST);
940 int fd = caglobals.ip.u4.fd;
942 uint32_t len = u_arraylist_length(iflist);
943 for (uint32_t i = 0; i < len; i++)
945 CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
950 if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
954 if (ifitem->family != AF_INET)
959 struct in_addr inaddr;
960 inaddr.s_addr = ifitem->ipv4addr;
961 mreq.imr_address = inaddr;
962 if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, &mreq, sizeof (mreq)))
964 OIC_LOG_V(ERROR, TAG, "send IP_MULTICAST_IF failed: %s (using defualt)",
967 sendData(fd, endpoint, data, datalen, "multicast", "ipv4");
971 void CAIPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
974 VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
975 VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
977 bool isSecure = (endpoint->flags & CA_SECURE) != 0;
981 endpoint->port = isSecure ? CA_SECURE_COAP : CA_COAP;
983 u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
986 OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
990 if ((endpoint->flags & CA_IPV6) && caglobals.ip.ipv6enabled)
992 sendMulticastData6(iflist, endpoint, data, datalen);
994 if ((endpoint->flags & CA_IPV4) && caglobals.ip.ipv4enabled)
996 sendMulticastData4(iflist, endpoint, data, datalen);
999 u_arraylist_destroy(iflist);
1003 if (!endpoint->port) // unicast discovery
1005 endpoint->port = isSecure ? CA_SECURE_COAP : CA_COAP;
1009 if (caglobals.ip.ipv6enabled && (endpoint->flags & CA_IPV6))
1011 fd = isSecure ? caglobals.ip.u6s.fd : caglobals.ip.u6.fd;
1012 #ifndef __WITH_DTLS__
1013 fd = caglobals.ip.u6.fd;
1015 sendData(fd, endpoint, data, datalen, "unicast", "ipv6");
1017 if (caglobals.ip.ipv4enabled && (endpoint->flags & CA_IPV4))
1019 fd = isSecure ? caglobals.ip.u4s.fd : caglobals.ip.u4.fd;
1020 #ifndef __WITH_DTLS__
1021 fd = caglobals.ip.u4.fd;
1023 sendData(fd, endpoint, data, datalen, "unicast", "ipv4");
1028 CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1030 VERIFY_NON_NULL(info, TAG, "info is NULL");
1031 VERIFY_NON_NULL(size, TAG, "size is NULL");
1033 u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
1036 OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
1037 return CA_STATUS_FAILED;
1040 uint32_t len = u_arraylist_length(iflist);
1041 uint32_t length = len;
1043 #ifdef __WITH_DTLS__
1044 //If DTLS is supported, each interface can support secure port as well
1048 CAEndpoint_t *eps = (CAEndpoint_t *)OICCalloc(length, sizeof (CAEndpoint_t));
1051 OIC_LOG(ERROR, TAG, "Malloc Failed");
1052 u_arraylist_destroy(iflist);
1053 return CA_MEMORY_ALLOC_FAILED;
1056 for (uint32_t i = 0, j = 0; i < len; i++)
1058 CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1064 eps[j].adapter = CA_ADAPTER_IP;
1065 eps[j].interface = 0;
1067 if (ifitem->family == AF_INET6)
1069 eps[j].flags = CA_IPV6;
1070 eps[j].port = caglobals.ip.u6.port;
1074 eps[j].flags = CA_IPV4;
1075 eps[j].port = caglobals.ip.u4.port;
1077 inet_ntop(AF_INET, &(ifitem->ipv4addr), eps[j].addr, MAX_ADDR_STR_SIZE_CA);
1080 #ifdef __WITH_DTLS__
1083 eps[j].adapter = CA_ADAPTER_IP;
1084 eps[j].interface = 0;
1086 if (ifitem->family == AF_INET6)
1088 eps[j].flags = CA_IPV6 | CA_SECURE;
1089 eps[j].port = caglobals.ip.u6s.port;
1093 eps[j].flags = CA_IPV4 | CA_SECURE;
1094 eps[j].port = caglobals.ip.u4s.port;
1095 inet_ntop(AF_INET, &(ifitem->ipv4addr), eps[j].addr, MAX_ADDR_STR_SIZE_CA);
1104 u_arraylist_destroy(iflist);
1106 return CA_STATUS_OK;
1109 void CAIPSetErrorHandler(CAIPErrorHandleCallback errorHandleCallback)
1111 g_ipErrorHandler = errorHandleCallback;