Imported Upstream version 1.2.0
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / ip_adapter / caipserver.c
1 /* ****************************************************************
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 "iotivity_config.h"
29 #include <sys/types.h>
30 #if !defined(_WIN32)
31 #include <sys/socket.h>
32 #endif
33
34 #if defined(_WIN32)
35 #include <assert.h>
36 #include <winsock2.h>
37 #include <ws2def.h>
38 #include <mswsock.h>
39 #include <ws2tcpip.h>
40 #endif
41
42 #include <stdio.h>
43 #if !defined(_MSC_VER)
44 #include <unistd.h>
45 #endif //!defined(_MSC_VER)
46 #include <sys/types.h>
47 #include <fcntl.h>
48 #if !defined(_WIN32)
49 #include <sys/select.h>
50 #include <arpa/inet.h>
51 #include <netinet/in.h>
52 #include <net/if.h>
53 #endif
54 #include <errno.h>
55 #ifdef __linux__
56 #include <linux/netlink.h>
57 #include <linux/rtnetlink.h>
58 #endif
59
60 #include <coap/pdu.h>
61 #include "caipinterface.h"
62 #include "caadapterutils.h"
63 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
64 #include "ca_adapter_net_ssl.h"
65 #endif
66 #include "camutex.h"
67 #include "oic_malloc.h"
68 #include "oic_string.h"
69
70 #define USE_IP_MREQN
71 #if defined(_WIN32)
72 #undef USE_IP_MREQN
73 #endif
74
75 /*
76  * Logging tag for module name
77  */
78 #define TAG "OIC_CA_IP_SERVER"
79
80 #define SELECT_TIMEOUT 1     // select() seconds (and termination latency)
81
82 #define IPv4_MULTICAST     "224.0.1.187"
83 static struct in_addr IPv4MulticastAddress = { 0 };
84
85 #define IPv6_DOMAINS       16
86 #define IPv6_MULTICAST_INT "ff01::158"
87 static struct in6_addr IPv6MulticastAddressInt;
88 #define IPv6_MULTICAST_LNK "ff02::158"
89 static struct in6_addr IPv6MulticastAddressLnk;
90 #define IPv6_MULTICAST_RLM "ff03::158"
91 static struct in6_addr IPv6MulticastAddressRlm;
92 #define IPv6_MULTICAST_ADM "ff04::158"
93 static struct in6_addr IPv6MulticastAddressAdm;
94 #define IPv6_MULTICAST_SIT "ff05::158"
95 static struct in6_addr IPv6MulticastAddressSit;
96 #define IPv6_MULTICAST_ORG "ff08::158"
97 static struct in6_addr IPv6MulticastAddressOrg;
98 #define IPv6_MULTICAST_GLB "ff0e::158"
99 static struct in6_addr IPv6MulticastAddressGlb;
100
101 static char *ipv6mcnames[IPv6_DOMAINS] = {
102     NULL,
103     IPv6_MULTICAST_INT,
104     IPv6_MULTICAST_LNK,
105     IPv6_MULTICAST_RLM,
106     IPv6_MULTICAST_ADM,
107     IPv6_MULTICAST_SIT,
108     NULL,
109     NULL,
110     IPv6_MULTICAST_ORG,
111     NULL,
112     NULL,
113     NULL,
114     NULL,
115     NULL,
116     IPv6_MULTICAST_GLB,
117     NULL
118 };
119
120 #if defined (_WIN32)
121 #define IFF_UP_RUNNING_FLAGS  (IFF_UP)
122
123     char* caips_get_error(){
124         static char buffer[32];
125         snprintf(buffer, 32, "%i", WSAGetLastError());
126         return buffer;
127     }
128 #define CAIPS_GET_ERROR \
129     caips_get_error()
130 #else
131 #define IFF_UP_RUNNING_FLAGS  (IFF_UP|IFF_RUNNING)
132
133 #define CAIPS_GET_ERROR \
134     strerror(errno)
135 #endif
136 static CAIPErrorHandleCallback g_ipErrorHandler = NULL;
137
138 static CAIPPacketReceivedCallback g_packetReceivedCallback = NULL;
139
140 static void CAFindReadyMessage();
141 #if !defined(WSA_WAIT_EVENT_0)
142 static void CASelectReturned(fd_set *readFds, int ret);
143 #else
144 static void CAEventReturned(CASocketFd_t socket);
145 #endif
146 static void CAProcessNewInterface(CAInterface_t *ifchanged);
147 static CAResult_t CAReceiveMessage(CASocketFd_t fd, CATransportFlags_t flags);
148
149 static void CAReceiveHandler(void *data)
150 {
151     (void)data;
152
153     while (!caglobals.ip.terminate)
154     {
155         CAFindReadyMessage();
156     }
157 }
158
159 #if !defined(WSA_WAIT_EVENT_0)
160
161 #define CLOSE_SOCKET(TYPE) \
162     if (caglobals.ip.TYPE.fd != OC_INVALID_SOCKET) \
163     { \
164         close(caglobals.ip.TYPE.fd); \
165         caglobals.ip.TYPE.fd = OC_INVALID_SOCKET; \
166     }
167
168 #define SET(TYPE, FDS) \
169     if (caglobals.ip.TYPE.fd != OC_INVALID_SOCKET) \
170     { \
171         FD_SET(caglobals.ip.TYPE.fd, FDS); \
172     }
173
174 #define ISSET(TYPE, FDS, FLAGS) \
175     if (caglobals.ip.TYPE.fd != OC_INVALID_SOCKET && FD_ISSET(caglobals.ip.TYPE.fd, FDS)) \
176     { \
177         fd = caglobals.ip.TYPE.fd; \
178         flags = FLAGS; \
179     }
180
181
182 static void CAFindReadyMessage()
183 {
184     fd_set readFds;
185     struct timeval timeout;
186
187     timeout.tv_sec = caglobals.ip.selectTimeout;
188     timeout.tv_usec = 0;
189     struct timeval *tv = caglobals.ip.selectTimeout == -1 ? NULL : &timeout;
190
191     FD_ZERO(&readFds);
192     SET(u6,  &readFds)
193     SET(u6s, &readFds)
194     SET(u4,  &readFds)
195     SET(u4s, &readFds)
196     SET(m6,  &readFds)
197     SET(m6s, &readFds)
198     SET(m4,  &readFds)
199     SET(m4s, &readFds)
200
201     if (caglobals.ip.shutdownFds[0] != -1)
202     {
203         FD_SET(caglobals.ip.shutdownFds[0], &readFds);
204     }
205     if (caglobals.ip.netlinkFd != OC_INVALID_SOCKET)
206     {
207         FD_SET(caglobals.ip.netlinkFd, &readFds);
208     }
209
210     int ret = select(caglobals.ip.maxfd + 1, &readFds, NULL, NULL, tv);
211
212     if (caglobals.ip.terminate)
213     {
214         OIC_LOG_V(DEBUG, TAG, "Packet receiver Stop request received.");
215         return;
216     }
217
218     if (ret <= 0)
219     {
220         if (ret < 0)
221         {
222             OIC_LOG_V(FATAL, TAG, "select error %s", CAIPS_GET_ERROR);
223         }
224         return;
225     }
226
227     CASelectReturned(&readFds, ret);
228 }
229
230 static void CASelectReturned(fd_set *readFds, int ret)
231 {
232     (void)ret;
233     CASocketFd_t fd = OC_INVALID_SOCKET;
234     CATransportFlags_t flags = CA_DEFAULT_FLAGS;
235
236     while (!caglobals.ip.terminate)
237     {
238         ISSET(u6,  readFds, CA_IPV6)
239         else ISSET(u6s, readFds, CA_IPV6 | CA_SECURE)
240         else ISSET(u4,  readFds, CA_IPV4)
241         else ISSET(u4s, readFds, CA_IPV4 | CA_SECURE)
242         else ISSET(m6,  readFds, CA_MULTICAST | CA_IPV6)
243         else ISSET(m6s, readFds, CA_MULTICAST | CA_IPV6 | CA_SECURE)
244         else ISSET(m4,  readFds, CA_MULTICAST | CA_IPV4)
245         else ISSET(m4s, readFds, CA_MULTICAST | CA_IPV4 | CA_SECURE)
246         else if ((caglobals.ip.netlinkFd != OC_INVALID_SOCKET) && FD_ISSET(caglobals.ip.netlinkFd, readFds))
247         {
248             CAInterface_t *ifchanged = CAFindInterfaceChange();
249             if (ifchanged)
250             {
251                 CAProcessNewInterface(ifchanged);
252                 OICFree(ifchanged);
253             }
254             break;
255         }
256         else if (FD_ISSET(caglobals.ip.shutdownFds[0], readFds))
257         {
258             char buf[10] = {0};
259             ssize_t len = read(caglobals.ip.shutdownFds[0], buf, sizeof (buf));
260             if (-1 == len)
261             {
262                 continue;
263             }
264             break;
265         }
266         else
267         {
268             break;
269         }
270         (void)CAReceiveMessage(fd, flags);
271         FD_CLR(fd, readFds);
272     }
273 }
274
275 #else // if defined(WSA_WAIT_EVENT_0)
276
277 #define CLOSE_SOCKET(TYPE) \
278     if (caglobals.ip.TYPE.fd != OC_INVALID_SOCKET) \
279     { \
280         closesocket(caglobals.ip.TYPE.fd); \
281         caglobals.ip.TYPE.fd = OC_INVALID_SOCKET; \
282     }
283
284 #define PUSH_HANDLE(HANDLE, ARRAY, INDEX) \
285 { \
286     ARRAY[INDEX] = HANDLE; \
287     INDEX++; \
288 }
289
290 // Turn handle into WSAEvent and push to ARRAY
291 #define PUSH_SOCKET(SOCKET, ARRAY, INDEX) \
292     if (SOCKET != OC_INVALID_SOCKET) \
293     { \
294         WSAEVENT NewEvent; \
295         NewEvent = WSACreateEvent(); \
296         if (WSA_INVALID_EVENT != NewEvent) \
297         { \
298             if (0 != WSAEventSelect(SOCKET, NewEvent, FD_READ)) \
299             { \
300                 OIC_LOG_V(ERROR, TAG, "WSAEventSelect failed 0x%08x ", WSAGetLastError()); \
301                 if (!WSACloseEvent(NewEvent)) \
302                 { \
303                     OIC_LOG_V(ERROR, TAG, "WSACloseEvent(NewEvent) failed 0x%08x", WSAGetLastError()); \
304                 } \
305             } \
306             else \
307             { \
308                 PUSH_HANDLE(NewEvent, ARRAY, INDEX); \
309             } \
310         } \
311         else \
312         { \
313             OIC_LOG_V(ERROR, TAG, "WSACreateEvent(NewEvent) failed 0x%08x", WSAGetLastError()); \
314         }\
315     }
316
317 #define INSERT_SOCKET(FD, ARRAY, INDEX) \
318     { \
319         if (OC_INVALID_SOCKET != FD) \
320         { \
321             ARRAY[INDEX] = FD; \
322         } \
323     }
324
325
326 // Inserts the socket into the SOCKET_ARRAY and pushes the socket event into EVENT_ARRAY
327 #define PUSH_IP_SOCKET(TYPE, EVENT_ARRAY, SOCKET_ARRAY, INDEX) \
328     { \
329         if (OC_INVALID_SOCKET != caglobals.ip.TYPE.fd) \
330         { \
331             INSERT_SOCKET(caglobals.ip.TYPE.fd, SOCKET_ARRAY, INDEX); \
332             PUSH_SOCKET(caglobals.ip.TYPE.fd, EVENT_ARRAY, INDEX); \
333         } \
334     }
335
336 #define IS_MATCHING_IP_SOCKET(TYPE, SOCKET, FLAGS) \
337     if ((caglobals.ip.TYPE.fd != OC_INVALID_SOCKET) && (caglobals.ip.TYPE.fd == SOCKET)) \
338     { \
339         fd = caglobals.ip.TYPE.fd; \
340         flags = FLAGS; \
341     }
342
343 #define EVENT_ARRAY_SIZE  10
344
345 static void CAFindReadyMessage()
346 {
347     CASocketFd_t socketArray[EVENT_ARRAY_SIZE];
348     HANDLE eventArray[EVENT_ARRAY_SIZE];
349     int arraySize = 0;
350     int eventIndex;
351
352     // socketArray and eventArray should have same number of elements
353     OC_STATIC_ASSERT(_countof(socketArray) == _countof(eventArray), "Arrays should have same number of elements");
354
355     PUSH_IP_SOCKET(u6,  eventArray, socketArray, arraySize);
356     PUSH_IP_SOCKET(u6s, eventArray, socketArray, arraySize);
357     PUSH_IP_SOCKET(u4,  eventArray, socketArray, arraySize);
358     PUSH_IP_SOCKET(u4s, eventArray, socketArray, arraySize);
359     PUSH_IP_SOCKET(m6,  eventArray, socketArray, arraySize);
360     PUSH_IP_SOCKET(m6s, eventArray, socketArray, arraySize);
361     PUSH_IP_SOCKET(m4,  eventArray, socketArray, arraySize);
362     PUSH_IP_SOCKET(m4s, eventArray, socketArray, arraySize);
363
364     if (WSA_INVALID_EVENT != caglobals.ip.shutdownEvent)
365     {
366         INSERT_SOCKET(OC_INVALID_SOCKET, socketArray, arraySize);
367         PUSH_HANDLE(caglobals.ip.shutdownEvent, eventArray, arraySize);
368     }
369
370     /** @todo Support netlink events */
371
372     // Should not have overflowed buffer
373     assert(arraySize <= (_countof(socketArray)));
374
375     // Timeout is unnecessary on Windows
376     assert(-1 == caglobals.ip.selectTimeout);
377
378     while (!caglobals.ip.terminate)
379     {
380         int ret = WSAWaitForMultipleEvents(arraySize, eventArray, FALSE, WSA_INFINITE, FALSE);
381
382         switch (ret)
383         {
384             case WSA_WAIT_FAILED:
385                 OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents returned WSA_WAIT_FAILED 0x%08x", WSAGetLastError());
386                 break;
387             case WSA_WAIT_IO_COMPLETION:
388                 OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents returned WSA_WAIT_IO_COMPLETION 0x%08x", WSAGetLastError());
389                 break;
390             case WSA_WAIT_TIMEOUT:
391                 OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents returned WSA_WAIT_TIMEOUT 0x%08x", WSAGetLastError());
392                 break;
393             default:
394                 eventIndex = ret - WSA_WAIT_EVENT_0;
395                 if ((eventIndex >= 0) && (eventIndex < arraySize))
396                 {
397                     if (false == WSAResetEvent(eventArray[eventIndex]))
398                     {
399                         OIC_LOG_V(ERROR, TAG, "WSAResetEvent failed 0x%08x", WSAGetLastError());
400                     }
401
402                     // Break out if shutdownEvent is triggered
403                     if ((caglobals.ip.shutdownEvent != WSA_INVALID_EVENT) &&
404                         (caglobals.ip.shutdownEvent == eventArray[eventIndex]))
405                     {
406                         break;
407                     }
408                     CAEventReturned(socketArray[eventIndex]);
409                 }
410                 else
411                 {
412                     OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents failed 0x%08x", WSAGetLastError());
413                 }
414                 break;
415         }
416
417     }
418
419     while (arraySize > 0)
420     {
421         arraySize--;
422         if (!WSACloseEvent(eventArray[arraySize]))
423         {
424             OIC_LOG_V(ERROR, TAG, "WSACloseEvent (Index %i) failed 0x%08x", arraySize, WSAGetLastError());
425         }
426     }
427
428     if (caglobals.ip.terminate)
429     {
430         caglobals.ip.shutdownEvent = WSA_INVALID_EVENT;
431         WSACleanup();
432     }
433 }
434
435 static void CAEventReturned(CASocketFd_t socket)
436 {
437     CASocketFd_t fd = OC_INVALID_SOCKET;
438     CATransportFlags_t flags = CA_DEFAULT_FLAGS;
439
440     while (!caglobals.ip.terminate)
441     {
442         IS_MATCHING_IP_SOCKET(u6,  socket, CA_IPV6)
443         else IS_MATCHING_IP_SOCKET(u6s, socket, CA_IPV6 | CA_SECURE)
444         else IS_MATCHING_IP_SOCKET(u4,  socket, CA_IPV4)
445         else IS_MATCHING_IP_SOCKET(u4s, socket, CA_IPV4 | CA_SECURE)
446         else IS_MATCHING_IP_SOCKET(m6,  socket, CA_MULTICAST | CA_IPV6)
447         else IS_MATCHING_IP_SOCKET(m6s, socket, CA_MULTICAST | CA_IPV6 | CA_SECURE)
448         else IS_MATCHING_IP_SOCKET(m4,  socket, CA_MULTICAST | CA_IPV4)
449         else IS_MATCHING_IP_SOCKET(m4s, socket, CA_MULTICAST | CA_IPV4 | CA_SECURE)
450         else
451         {
452             break;
453         }
454         (void)CAReceiveMessage(socket, flags);
455         // We will never get more than one match per socket, so always break.
456         break;
457     }
458 }
459
460 #endif
461
462 void CADeInitializeIPGlobals()
463 {
464     CLOSE_SOCKET(u6);
465     CLOSE_SOCKET(u6s);
466     CLOSE_SOCKET(u4);
467     CLOSE_SOCKET(u4s);
468     CLOSE_SOCKET(m6);
469     CLOSE_SOCKET(m6s);
470     CLOSE_SOCKET(m4);
471     CLOSE_SOCKET(m4s);
472
473     if (caglobals.ip.netlinkFd != OC_INVALID_SOCKET)
474     {
475 #ifdef _WIN32
476         closesocket(caglobals.ip.netlinkFd);
477 #else
478         close(caglobals.ip.netlinkFd);
479 #endif
480         caglobals.ip.netlinkFd = OC_INVALID_SOCKET;
481     }
482 }
483
484 static CAResult_t CAReceiveMessage(CASocketFd_t fd, CATransportFlags_t flags)
485 {
486     char recvBuffer[COAP_MAX_PDU_SIZE] = {0};
487
488     size_t len = 0;
489     int level = 0;
490     int type = 0;
491     int namelen = 0;
492     struct sockaddr_storage srcAddr = { .ss_family = 0 };
493     unsigned char *pktinfo = NULL;
494 #if !defined(WSA_CMSG_DATA)
495     struct cmsghdr *cmp = NULL;
496     struct iovec iov = { .iov_base = recvBuffer, .iov_len = sizeof (recvBuffer) };
497     union control
498     {
499         struct cmsghdr cmsg;
500         unsigned char data[CMSG_SPACE(sizeof (struct in6_pktinfo))];
501     } cmsg;
502
503     if (flags & CA_IPV6)
504     {
505         namelen = sizeof (struct sockaddr_in6);
506         level = IPPROTO_IPV6;
507         type = IPV6_PKTINFO;
508         len = sizeof (struct in6_pktinfo);
509     }
510     else
511     {
512         namelen = sizeof (struct sockaddr_in);
513         level = IPPROTO_IP;
514         type = IP_PKTINFO;
515         len = sizeof (struct in6_pktinfo);
516     }
517
518     struct msghdr msg = { .msg_name = &srcAddr,
519                           .msg_namelen = namelen,
520                           .msg_iov = &iov,
521                           .msg_iovlen = 1,
522                           .msg_control = &cmsg,
523                           .msg_controllen = CMSG_SPACE(len) };
524
525     ssize_t recvLen = recvmsg(fd, &msg, flags);
526     if (OC_SOCKET_ERROR == recvLen)
527     {
528         OIC_LOG_V(ERROR, TAG, "Recvfrom failed %s", strerror(errno));
529         return CA_STATUS_FAILED;
530     }
531
532     if (flags & CA_MULTICAST)
533     {
534         for (cmp = CMSG_FIRSTHDR(&msg); cmp != NULL; cmp = CMSG_NXTHDR(&msg, cmp))
535         {
536             if (cmp->cmsg_level == level && cmp->cmsg_type == type)
537             {
538                 pktinfo = CMSG_DATA(cmp);
539             }
540         }
541     }
542 #else // if defined(WSA_CMSG_DATA)
543     union control
544     {
545         WSACMSGHDR cmsg;
546         uint8_t data[WSA_CMSG_SPACE(sizeof (IN6_PKTINFO))];
547     } cmsg;
548     memset(&cmsg, 0, sizeof(cmsg));
549
550     if (flags & CA_IPV6)
551     {
552         namelen  = sizeof (struct sockaddr_in6);
553         level = IPPROTO_IPV6;
554         type = IPV6_PKTINFO;
555     }
556     else
557     {
558         namelen = sizeof (struct sockaddr_in);
559         level = IPPROTO_IP;
560         type = IP_PKTINFO;
561     }
562
563     WSABUF iov = {.len = sizeof (recvBuffer), .buf = recvBuffer};
564     WSAMSG msg = {.name = (PSOCKADDR)&srcAddr,
565                   .namelen = namelen,
566                   .lpBuffers = &iov,
567                   .dwBufferCount = 1,
568                   .Control = {.buf = cmsg.data, .len = sizeof (cmsg)}
569                  };
570
571     uint32_t recvLen = 0;
572     uint32_t ret = caglobals.ip.wsaRecvMsg(fd, &msg, &recvLen, 0,0);
573     OIC_LOG_V(DEBUG, TAG, "WSARecvMsg recvd %u bytes", recvLen);
574     if (OC_SOCKET_ERROR == ret)
575     {
576         OIC_LOG_V(ERROR, TAG, "WSARecvMsg failed %i", WSAGetLastError());
577     }
578
579     if (flags & CA_MULTICAST)
580     {
581         for (WSACMSGHDR *cmp = WSA_CMSG_FIRSTHDR(&msg); cmp != NULL;
582              cmp = WSA_CMSG_NXTHDR(&msg, cmp))
583         {
584             if (cmp->cmsg_level == level && cmp->cmsg_type == type)
585             {
586                 pktinfo = WSA_CMSG_DATA(cmp);
587             }
588         }
589     }
590 #endif // !defined(WSA_CMSG_DATA)
591     CASecureEndpoint_t sep = {.endpoint = {.adapter = CA_ADAPTER_IP, .flags = flags}};
592
593     if (flags & CA_IPV6)
594     {
595         /** @todo figure out correct usage for ifindex, and sin6_scope_id.*/
596         if ((flags & CA_MULTICAST) && pktinfo)
597         {
598             struct in6_addr *addr = &(((struct in6_pktinfo *)pktinfo)->ipi6_addr);
599             unsigned char topbits = ((unsigned char *)addr)[0];
600             if (topbits != 0xff)
601             {
602                 sep.endpoint.flags &= ~CA_MULTICAST;
603             }
604         }
605     }
606     else
607     {
608         if ((flags & CA_MULTICAST) && pktinfo)
609         {
610             struct in_addr *addr = &((struct in_pktinfo *)pktinfo)->ipi_addr;
611             uint32_t host = ntohl(addr->s_addr);
612             unsigned char topbits = ((unsigned char *)&host)[3];
613             if (topbits < 224 || topbits > 239)
614             {
615                 sep.endpoint.flags &= ~CA_MULTICAST;
616             }
617         }
618     }
619
620     CAConvertAddrToName(&srcAddr, namelen, sep.endpoint.addr, &sep.endpoint.port);
621
622     if (flags & CA_SECURE)
623     {
624 #ifdef __WITH_DTLS__
625         int ret = CAdecryptSsl(&sep, (uint8_t *)recvBuffer, recvLen);
626         OIC_LOG_V(DEBUG, TAG, "CAdecryptSsl returns [%d]", ret);
627 #else
628         OIC_LOG(ERROR, TAG, "Encrypted message but no DTLS");
629 #endif
630     }
631     else
632     {
633         if (g_packetReceivedCallback)
634         {
635             g_packetReceivedCallback(&sep, recvBuffer, recvLen);
636         }
637     }
638
639     return CA_STATUS_OK;
640
641 }
642
643 void CAIPPullData()
644 {
645     OIC_LOG(DEBUG, TAG, "IN");
646     OIC_LOG(DEBUG, TAG, "OUT");
647 }
648
649 static CASocketFd_t CACreateSocket(int family, uint16_t *port, bool isMulticast)
650 {
651     int socktype = SOCK_DGRAM;
652 #ifdef SOCK_CLOEXEC
653     socktype |= SOCK_CLOEXEC;
654 #endif
655     CASocketFd_t fd = socket(family, socktype, IPPROTO_UDP);
656     if (OC_INVALID_SOCKET == fd)
657     {
658         OIC_LOG_V(ERROR, TAG, "create socket failed: %s", CAIPS_GET_ERROR);
659         return OC_INVALID_SOCKET;
660     }
661
662 #if !defined(SOCK_CLOEXEC) && defined(FD_CLOEXEC)
663     int fl = fcntl(fd, F_GETFD);
664     if (-1 == fl || -1 == fcntl(fd, F_SETFD, fl|FD_CLOEXEC))
665     {
666         OIC_LOG_V(ERROR, TAG, "set FD_CLOEXEC failed: %s", strerror(errno));
667         close(fd);
668         return OC_INVALID_SOCKET;
669     }
670 #endif
671     struct sockaddr_storage sa = { .ss_family = family };
672     socklen_t socklen = 0;
673
674     if (family == AF_INET6)
675     {
676         int on = 1;
677
678         if (OC_SOCKET_ERROR == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, OPTVAL_T(&on), sizeof (on)))
679         {
680             OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", CAIPS_GET_ERROR);
681         }
682
683         if (isMulticast && *port) // only do this for multicast ports
684         {
685 #if defined(IPV6_RECVPKTINFO)
686             if (OC_SOCKET_ERROR == setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof (on)))
687 #else
688             if (OC_SOCKET_ERROR == setsockopt(fd, IPPROTO_IPV6, IPV6_PKTINFO, OPTVAL_T(&on), sizeof (on)))
689 #endif
690             {
691                 OIC_LOG_V(ERROR, TAG, "IPV6_RECVPKTINFO failed: %s",CAIPS_GET_ERROR);
692             }
693         }
694
695         ((struct sockaddr_in6 *)&sa)->sin6_port = htons(*port);
696         socklen = sizeof (struct sockaddr_in6);
697     }
698     else
699     {
700         if (isMulticast && *port) // only do this for multicast ports
701         {
702             int on = 1;
703             if (OC_SOCKET_ERROR == setsockopt(fd, IPPROTO_IP, IP_PKTINFO, OPTVAL_T(&on), sizeof (on)))
704             {
705                 OIC_LOG_V(ERROR, TAG, "IP_PKTINFO failed: %s", CAIPS_GET_ERROR);
706             }
707         }
708
709         ((struct sockaddr_in *)&sa)->sin_port = htons(*port);
710         socklen = sizeof (struct sockaddr_in);
711     }
712
713     if (isMulticast && *port) // use the given port
714     {
715         int on = 1;
716         if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof (on)))
717         {
718             OIC_LOG_V(ERROR, TAG, "SO_REUSEADDR failed: %s", CAIPS_GET_ERROR);
719 #ifdef _WIN32
720             closesocket(fd);
721 #else
722             close(fd);
723 #endif
724             return OC_INVALID_SOCKET;
725         }
726     }
727
728     if (OC_SOCKET_ERROR == bind(fd, (struct sockaddr *)&sa, socklen))
729     {
730         OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", CAIPS_GET_ERROR);
731 #ifdef _WIN32
732         closesocket(fd);
733 #else
734         close(fd);
735 #endif
736         return OC_INVALID_SOCKET;
737     }
738
739     if (!*port) // return the assigned port
740     {
741         if (OC_SOCKET_ERROR == getsockname(fd, (struct sockaddr *)&sa, &socklen))
742         {
743             OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", CAIPS_GET_ERROR);
744 #ifdef _WIN32
745             closesocket(fd);
746 #else
747             close(fd);
748 #endif
749             return OC_INVALID_SOCKET;
750         }
751         *port = ntohs(family == AF_INET6 ?
752                       ((struct sockaddr_in6 *)&sa)->sin6_port :
753                       ((struct sockaddr_in *)&sa)->sin_port);
754     }
755
756     return fd;
757 }
758
759 #define CHECKFD(FD) \
760     if (FD > caglobals.ip.maxfd) \
761         caglobals.ip.maxfd = FD;
762 #define NEWSOCKET(FAMILY, NAME, MULTICAST) \
763     caglobals.ip.NAME.fd = CACreateSocket(FAMILY, &caglobals.ip.NAME.port, MULTICAST); \
764     if (caglobals.ip.NAME.fd == OC_INVALID_SOCKET) \
765     {   \
766         caglobals.ip.NAME.port = 0; \
767         caglobals.ip.NAME.fd = CACreateSocket(FAMILY, &caglobals.ip.NAME.port, MULTICAST); \
768     }   \
769     CHECKFD(caglobals.ip.NAME.fd)
770
771 static void CAInitializeNetlink()
772 {
773     caglobals.ip.netlinkFd = OC_INVALID_SOCKET;
774 #ifdef __linux__
775     // create NETLINK fd for interface change notifications
776     struct sockaddr_nl sa = { AF_NETLINK, 0, 0, RTMGRP_LINK };
777
778     caglobals.ip.netlinkFd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC, NETLINK_ROUTE);
779     if (caglobals.ip.netlinkFd == OC_INVALID_SOCKET)
780     {
781         OIC_LOG_V(ERROR, TAG, "netlink socket failed: %s", strerror(errno));
782     }
783     else
784     {
785         int r = bind(caglobals.ip.netlinkFd, (struct sockaddr *)&sa, sizeof (sa));
786         if (r)
787         {
788             OIC_LOG_V(ERROR, TAG, "netlink bind failed: %s", strerror(errno));
789             close(caglobals.ip.netlinkFd);
790             caglobals.ip.netlinkFd = OC_INVALID_SOCKET;
791         }
792         else
793         {
794             CHECKFD(caglobals.ip.netlinkFd);
795         }
796     }
797 #endif
798 }
799
800 static void CAInitializeFastShutdownMechanism()
801 {
802     caglobals.ip.selectTimeout = -1; // don't poll for shutdown
803     int ret = -1;
804 #if defined(WSA_WAIT_EVENT_0)
805     caglobals.ip.shutdownEvent = WSACreateEvent();
806     if (WSA_INVALID_EVENT != caglobals.ip.shutdownEvent)
807     {
808         ret = 0;
809     }
810 #elif defined(HAVE_PIPE2)
811     ret = pipe2(caglobals.ip.shutdownFds, O_CLOEXEC);
812     CHECKFD(caglobals.ip.shutdownFds[0]);
813     CHECKFD(caglobals.ip.shutdownFds[1]);
814 #else
815     ret = pipe(caglobals.ip.shutdownFds);
816     if (-1 != ret)
817     {
818         ret = fcntl(caglobals.ip.shutdownFds[0], F_GETFD);
819         if (-1 != ret)
820         {
821             ret = fcntl(caglobals.ip.shutdownFds[0], F_SETFD, ret|FD_CLOEXEC);
822         }
823         if (-1 != ret)
824         {
825             ret = fcntl(caglobals.ip.shutdownFds[1], F_GETFD);
826         }
827         if (-1 != ret)
828         {
829             ret = fcntl(caglobals.ip.shutdownFds[1], F_SETFD, ret|FD_CLOEXEC);
830         }
831         if (-1 == ret)
832         {
833             close(caglobals.ip.shutdownFds[1]);
834             close(caglobals.ip.shutdownFds[0]);
835             caglobals.ip.shutdownFds[0] = -1;
836             caglobals.ip.shutdownFds[1] = -1;
837         }
838     }
839     CHECKFD(caglobals.ip.shutdownFds[0]);
840     CHECKFD(caglobals.ip.shutdownFds[1]);
841 #endif
842     if (-1 == ret)
843     {
844         OIC_LOG_V(ERROR, TAG, "fast shutdown mechanism init failed: %s", CAIPS_GET_ERROR);
845         caglobals.ip.selectTimeout = SELECT_TIMEOUT; //poll needed for shutdown
846     }
847 }
848
849 CAResult_t CAIPStartServer(const ca_thread_pool_t threadPool)
850 {
851     CAResult_t res = CA_STATUS_OK;
852
853     if (caglobals.ip.started)
854     {
855         return res;
856     }
857 #if defined (_WIN32)
858     WORD wVersionRequested = MAKEWORD(2, 2);
859     WSADATA wsaData ={.wVersion = 0};
860     int err = WSAStartup(wVersionRequested, &wsaData);
861     if (err != 0)
862     {
863         OIC_LOG_V(ERROR, TAG, "WSAStartup failed: %i", err);
864         return CA_STATUS_FAILED;
865     }
866     OIC_LOG(DEBUG, TAG, "WSAStartup Succeeded");
867 #endif
868     if (!IPv4MulticastAddress.s_addr)
869     {
870         (void)inet_pton(AF_INET, IPv4_MULTICAST, &IPv4MulticastAddress);
871         (void)inet_pton(AF_INET6, IPv6_MULTICAST_INT, &IPv6MulticastAddressInt);
872         (void)inet_pton(AF_INET6, IPv6_MULTICAST_LNK, &IPv6MulticastAddressLnk);
873         (void)inet_pton(AF_INET6, IPv6_MULTICAST_RLM, &IPv6MulticastAddressRlm);
874         (void)inet_pton(AF_INET6, IPv6_MULTICAST_ADM, &IPv6MulticastAddressAdm);
875         (void)inet_pton(AF_INET6, IPv6_MULTICAST_SIT, &IPv6MulticastAddressSit);
876         (void)inet_pton(AF_INET6, IPv6_MULTICAST_ORG, &IPv6MulticastAddressOrg);
877         (void)inet_pton(AF_INET6, IPv6_MULTICAST_GLB, &IPv6MulticastAddressGlb);
878     }
879
880     if (!caglobals.ip.ipv6enabled && !caglobals.ip.ipv4enabled)
881     {
882         caglobals.ip.ipv4enabled = true;  // only needed to run CA tests
883     }
884
885     if (caglobals.ip.ipv6enabled)
886     {
887         NEWSOCKET(AF_INET6, u6, false)
888         NEWSOCKET(AF_INET6, u6s, false)
889         NEWSOCKET(AF_INET6, m6, true)
890         NEWSOCKET(AF_INET6, m6s, true)
891         OIC_LOG_V(INFO, TAG, "IPv6 unicast port: %u", caglobals.ip.u6.port);
892     }
893     if (caglobals.ip.ipv4enabled)
894     {
895         NEWSOCKET(AF_INET, u4, false)
896         NEWSOCKET(AF_INET, u4s, false)
897         NEWSOCKET(AF_INET, m4, true)
898         NEWSOCKET(AF_INET, m4s, true)
899         OIC_LOG_V(INFO, TAG, "IPv4 unicast port: %u", caglobals.ip.u4.port);
900     }
901
902     OIC_LOG_V(DEBUG, TAG,
903               "socket summary: u6=%d, u6s=%d, u4=%d, u4s=%d, m6=%d, m6s=%d, m4=%d, m4s=%d",
904               caglobals.ip.u6.fd, caglobals.ip.u6s.fd, caglobals.ip.u4.fd, caglobals.ip.u4s.fd,
905               caglobals.ip.m6.fd, caglobals.ip.m6s.fd, caglobals.ip.m4.fd, caglobals.ip.m4s.fd);
906
907     OIC_LOG_V(DEBUG, TAG,
908               "port summary: u6 port=%d, u6s port=%d, u4 port=%d, u4s port=%d, m6 port=%d,"
909               "m6s port=%d, m4 port=%d, m4s port=%d",
910               caglobals.ip.u6.port, caglobals.ip.u6s.port, caglobals.ip.u4.port,
911               caglobals.ip.u4s.port, caglobals.ip.m6.port, caglobals.ip.m6s.port,
912               caglobals.ip.m4.port, caglobals.ip.m4s.port);
913 #if defined (SIO_GET_EXTENSION_FUNCTION_POINTER)
914     caglobals.ip.wsaRecvMsg = NULL;
915     GUID GuidWSARecvMsg = WSAID_WSARECVMSG;
916     DWORD copied = 0;
917     err = WSAIoctl(caglobals.ip.u4.fd, SIO_GET_EXTENSION_FUNCTION_POINTER, &GuidWSARecvMsg, sizeof(GuidWSARecvMsg), &(caglobals.ip.wsaRecvMsg), sizeof(caglobals.ip.wsaRecvMsg), &copied, 0, 0);
918     if (0 != err)
919     {
920         OIC_LOG_V(ERROR, TAG, "WSAIoctl failed %i", WSAGetLastError());
921         return CA_STATUS_FAILED;
922     }
923 #endif
924     // set up appropriate FD mechanism for fast shutdown
925     CAInitializeFastShutdownMechanism();
926
927     // create source of network interface change notifications
928     CAInitializeNetlink();
929
930     caglobals.ip.selectTimeout = CAGetPollingInterval(caglobals.ip.selectTimeout);
931
932     res = CAIPStartListenServer();
933     if (CA_STATUS_OK != res)
934     {
935         OIC_LOG_V(ERROR, TAG, "Failed to start listening server![%d]", res);
936         return res;
937     }
938
939     caglobals.ip.terminate = false;
940     res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
941     if (CA_STATUS_OK != res)
942     {
943         OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
944         return res;
945     }
946     OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
947
948     caglobals.ip.started = true;
949     return CA_STATUS_OK;
950 }
951
952 void CAIPStopServer()
953 {
954     caglobals.ip.started = false;
955     caglobals.ip.terminate = true;
956
957 #if !defined(WSA_WAIT_EVENT_0)
958     if (caglobals.ip.shutdownFds[1] != -1)
959     {
960         close(caglobals.ip.shutdownFds[1]);
961         // receive thread will stop immediately
962     }
963     else
964     {
965         // receive thread will stop in SELECT_TIMEOUT seconds.
966     }
967 #else
968     // receive thread will stop immediately.
969     if (!WSASetEvent(caglobals.ip.shutdownEvent))
970     {
971         OIC_LOG_V(DEBUG, TAG, "set shutdown event failed: %#08X", GetLastError());
972     }
973 #endif
974 }
975
976 void CAWakeUpForChange()
977 {
978 #if !defined(WSA_WAIT_EVENT_0)
979     if (caglobals.ip.shutdownFds[1] != -1)
980     {
981         ssize_t len = 0;
982         do
983         {
984             len = write(caglobals.ip.shutdownFds[1], "w", 1);
985         } while ((len == -1) && (errno == EINTR));
986         if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
987         {
988             OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
989         }
990     }
991 #else
992     if (!WSASetEvent(caglobals.ip.shutdownEvent))
993     {
994         OIC_LOG_V(DEBUG, TAG, "set shutdown event failed: %#08X", GetLastError());
995     }
996 #endif
997 }
998
999 static void applyMulticastToInterface4(uint32_t ifindex)
1000 {
1001     if (!caglobals.ip.ipv4enabled)
1002     {
1003         return;
1004     }
1005
1006 #if defined(USE_IP_MREQN)
1007     struct ip_mreqn mreq = { .imr_multiaddr = IPv4MulticastAddress,
1008                              .imr_address.s_addr = htonl(INADDR_ANY),
1009                              .imr_ifindex = ifindex };
1010 #else
1011     struct ip_mreq mreq  = { .imr_multiaddr.s_addr = IPv4MulticastAddress.s_addr,
1012                              .imr_interface.s_addr = htonl(ifindex) };
1013 #endif
1014
1015     int ret = setsockopt(caglobals.ip.m4.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, OPTVAL_T(&mreq), sizeof (mreq));
1016     if (OC_SOCKET_ERROR == ret)
1017     {
1018 #if !defined(WSAEINVAL)
1019         if (EADDRINUSE != errno)
1020 #else
1021         if (WSAEINVAL != WSAGetLastError()) // Joining multicast group more than once (IPv4 Flavor)
1022 #endif
1023         {
1024             OIC_LOG_V(ERROR, TAG, "       IPv4 IP_ADD_MEMBERSHIP failed: %s", CAIPS_GET_ERROR);
1025         }
1026     }
1027     ret = setsockopt(caglobals.ip.m4s.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, OPTVAL_T(&mreq), sizeof (mreq));
1028     if (OC_SOCKET_ERROR == ret)
1029     {
1030 #if !defined(WSAEINVAL)
1031         if (EADDRINUSE != errno)
1032 #else
1033         if (WSAEINVAL != WSAGetLastError()) // Joining multicast group more than once (IPv4 Flavor)
1034 #endif
1035         {
1036             OIC_LOG_V(ERROR, TAG, "SECURE IPv4 IP_ADD_MEMBERSHIP failed: %s", CAIPS_GET_ERROR);
1037         }
1038     }
1039 }
1040
1041 static void applyMulticast6(int fd, struct in6_addr *addr, uint32_t ifindex)
1042 {
1043     struct ipv6_mreq mreq = {.ipv6mr_multiaddr = {0},
1044                              .ipv6mr_interface = ifindex };
1045
1046     // VS2013 has problems with struct copies inside struct initializers, so copy separately.
1047     mreq.ipv6mr_multiaddr = *addr;
1048
1049     int ret = setsockopt(fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, OPTVAL_T(&mreq), sizeof (mreq));
1050     if (OC_SOCKET_ERROR == ret)
1051     {
1052 #if !defined(_WIN32)
1053                 if (EADDRINUSE != errno)
1054 #else
1055                 if (WSAEINVAL != WSAGetLastError()) // Joining multicast group more than once (IPv6 Flavor)
1056 #endif
1057         {
1058             OIC_LOG_V(ERROR, TAG, "IPv6 IPV6_JOIN_GROUP failed: %s", CAIPS_GET_ERROR);
1059         }
1060     }
1061 }
1062
1063 static void applyMulticastToInterface6(uint32_t ifindex)
1064 {
1065     if (!caglobals.ip.ipv6enabled)
1066     {
1067         return;
1068     }
1069     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressInt, ifindex);
1070     applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressLnk, ifindex);
1071     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressRlm, ifindex);
1072     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressAdm, ifindex);
1073     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressSit, ifindex);
1074     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressOrg, ifindex);
1075     //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressGlb, ifindex);
1076
1077     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressInt, ifindex);
1078     applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressLnk, ifindex);
1079     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressRlm, ifindex);
1080     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressAdm, ifindex);
1081     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressSit, ifindex);
1082     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressOrg, ifindex);
1083     //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressGlb, ifindex);
1084 }
1085
1086 CAResult_t CAIPStartListenServer()
1087 {
1088     u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
1089     if (!iflist)
1090     {
1091         OIC_LOG_V(ERROR, TAG, "CAIPGetInterfaceInformation() failed: %s", strerror(errno));
1092         return CA_STATUS_FAILED;
1093     }
1094
1095     uint32_t len = u_arraylist_length(iflist);
1096     OIC_LOG_V(DEBUG, TAG, "IP network interfaces found: %d", len);
1097
1098     for (uint32_t i = 0; i < len; i++)
1099     {
1100         CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1101
1102         if (!ifitem)
1103         {
1104             continue;
1105         }
1106         if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
1107         {
1108             continue;
1109         }
1110         if (ifitem->family == AF_INET)
1111         {
1112             OIC_LOG_V(DEBUG, TAG, "Adding IPv4 interface %i to multicast group", ifitem->index);
1113             applyMulticastToInterface4(ifitem->index);
1114         }
1115         if (ifitem->family == AF_INET6)
1116         {
1117             OIC_LOG_V(DEBUG, TAG, "Adding IPv6 interface %i to multicast group", ifitem->index);
1118             applyMulticastToInterface6(ifitem->index);
1119         }
1120     }
1121
1122     u_arraylist_destroy(iflist);
1123     return CA_STATUS_OK;
1124 }
1125
1126 CAResult_t CAIPStopListenServer()
1127 {
1128     u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
1129     if (!iflist)
1130     {
1131         OIC_LOG_V(ERROR, TAG, "Get interface info failed: %s", strerror(errno));
1132         return CA_STATUS_FAILED;
1133     }
1134
1135     uint32_t len = u_arraylist_length(iflist);
1136     OIC_LOG_V(DEBUG, TAG, "IP network interfaces found: %d", len);
1137
1138     for (uint32_t i = 0; i < len; i++)
1139     {
1140         CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1141
1142         if (!ifitem)
1143         {
1144             continue;
1145         }
1146         if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
1147         {
1148             continue;
1149         }
1150         if (ifitem->family == AF_INET)
1151         {
1152             CLOSE_SOCKET(m4);
1153             CLOSE_SOCKET(m4s);
1154             OIC_LOG_V(DEBUG, TAG, "IPv4 network interface: %s cloed", ifitem->name);
1155         }
1156         if (ifitem->family == AF_INET6)
1157         {
1158             CLOSE_SOCKET(m6);
1159             CLOSE_SOCKET(m6s);
1160             OIC_LOG_V(DEBUG, TAG, "IPv6 network interface: %s", ifitem->name);
1161         }
1162     }
1163     u_arraylist_destroy(iflist);
1164     return CA_STATUS_OK;
1165 }
1166
1167 static void CAProcessNewInterface(CAInterface_t *ifitem)
1168 {
1169     if (!ifitem)
1170     {
1171         OIC_LOG(DEBUG, TAG, "ifitem is null");
1172         return;
1173     }
1174
1175     if (ifitem->family == AF_INET6)
1176     {
1177         applyMulticastToInterface6(ifitem->index);
1178     }
1179     if (ifitem->family == AF_INET)
1180     {
1181         applyMulticastToInterface4(ifitem->index);
1182     }
1183 }
1184
1185 void CAIPSetPacketReceiveCallback(CAIPPacketReceivedCallback callback)
1186 {
1187     g_packetReceivedCallback = callback;
1188 }
1189
1190 void CAIPSetConnectionStateChangeCallback(CAIPConnectionStateChangeCallback callback)
1191 {
1192     CAIPSetNetworkMonitorCallback(callback);
1193 }
1194
1195 static void sendData(int fd, const CAEndpoint_t *endpoint,
1196                      const void *data, uint32_t dlen,
1197                      const char *cast, const char *fam)
1198 {
1199     OIC_LOG(DEBUG, TAG, "IN");
1200
1201     if (!endpoint)
1202     {
1203         OIC_LOG(DEBUG, TAG, "endpoint is null");
1204         if (g_ipErrorHandler)
1205         {
1206             g_ipErrorHandler(endpoint, data, dlen, CA_STATUS_INVALID_PARAM);
1207         }
1208         return;
1209     }
1210
1211     (void)cast;  // eliminates release warning
1212     (void)fam;
1213
1214     struct sockaddr_storage sock = { .ss_family = 0 };
1215     CAConvertNameToAddr(endpoint->addr, endpoint->port, &sock);
1216
1217     socklen_t socklen = 0;
1218     if (sock.ss_family == AF_INET6)
1219     {
1220         /** @todo figure out correct usage for ifindex, and sin6_scope_id */
1221         socklen = sizeof(struct sockaddr_in6);
1222     }
1223     else
1224     {
1225         socklen = sizeof(struct sockaddr_in);
1226     }
1227
1228 #ifdef TB_LOG
1229     const char *secure = (endpoint->flags & CA_SECURE) ? "secure " : "";
1230 #endif
1231 #if !defined(_WIN32)
1232     ssize_t len = sendto(fd, data, dlen, 0, (struct sockaddr *)&sock, socklen);
1233     if (OC_SOCKET_ERROR == len)
1234     {
1235          // If logging is not defined/enabled.
1236         if (g_ipErrorHandler)
1237         {
1238             g_ipErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
1239         }
1240         OIC_LOG_V(ERROR, TAG, "%s%s %s sendTo failed: %s", secure, cast, fam, strerror(errno));
1241     }
1242     else
1243     {
1244         OIC_LOG_V(INFO, TAG, "%s%s %s sendTo is successful: %zd bytes", secure, cast, fam, len);
1245     }
1246 #else
1247     int err = 0;
1248     int len = 0;
1249     int sent = 0;
1250     do {
1251         len = sendto(fd, ((char*)data) + sent, dlen - sent, 0, (struct sockaddr *)&sock, socklen);
1252         if (OC_SOCKET_ERROR == len)
1253         {
1254             err = WSAGetLastError();
1255             if ((WSAEWOULDBLOCK != err) && (WSAENOBUFS != err))
1256             {
1257                  // If logging is not defined/enabled.
1258                 if (g_ipErrorHandler)
1259                 {
1260                     g_ipErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
1261                 }
1262
1263                 OIC_LOG_V(ERROR, TAG, "%s%s %s sendTo failed: %i", secure, cast, fam, err);
1264             }
1265         }
1266         else
1267         {
1268             sent += len;
1269             if (sent != len)
1270             {
1271                 OIC_LOG_V(DEBUG, TAG, "%s%s %s sendTo (Partial Send) is successful: "
1272                                       "currently sent: %ld bytes, "
1273                                       "total sent: %ld bytes, "
1274                                       "remaining: %ld bytes",
1275                                       secure, cast, fam, len, sent, dlen-sent);
1276             }
1277             else
1278             {
1279                 OIC_LOG_V(INFO, TAG, "%s%s %s sendTo is successful: %ld bytes",
1280                                      secure, cast, fam, len);
1281             }
1282         }
1283     } while ((OC_SOCKET_ERROR == len) && ((WSAEWOULDBLOCK == err) || (WSAENOBUFS == err)) || (sent < dlen));
1284 #endif
1285 }
1286
1287 static void sendMulticastData6(const u_arraylist_t *iflist,
1288                                CAEndpoint_t *endpoint,
1289                                const void *data, uint32_t datalen)
1290 {
1291     if (!endpoint)
1292     {
1293         OIC_LOG(DEBUG, TAG, "endpoint is null");
1294         return;
1295     }
1296
1297     int scope = endpoint->flags & CA_SCOPE_MASK;
1298     char *ipv6mcname = ipv6mcnames[scope];
1299     if (!ipv6mcname)
1300     {
1301         OIC_LOG_V(INFO, TAG, "IPv6 multicast scope invalid: %d", scope);
1302         return;
1303     }
1304     OICStrcpy(endpoint->addr, sizeof(endpoint->addr), ipv6mcname);
1305     int fd = caglobals.ip.u6.fd;
1306
1307     uint32_t len = u_arraylist_length(iflist);
1308     for (uint32_t i = 0; i < len; i++)
1309     {
1310         CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1311         if (!ifitem)
1312         {
1313             continue;
1314         }
1315         if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
1316         {
1317             continue;
1318         }
1319         if (ifitem->family != AF_INET6)
1320         {
1321             continue;
1322         }
1323
1324         int index = ifitem->index;
1325         if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, OPTVAL_T(&index), sizeof (index)))
1326         {
1327             OIC_LOG_V(ERROR, TAG, "setsockopt6 failed: %s", CAIPS_GET_ERROR);
1328             return;
1329         }
1330         sendData(fd, endpoint, data, datalen, "multicast", "ipv6");
1331     }
1332 }
1333
1334 static void sendMulticastData4(const u_arraylist_t *iflist,
1335                                CAEndpoint_t *endpoint,
1336                                const void *data, uint32_t datalen)
1337 {
1338     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
1339
1340 #if defined(USE_IP_MREQN)
1341     struct ip_mreqn mreq = { .imr_multiaddr = IPv4MulticastAddress,
1342                              .imr_address.s_addr = htonl(INADDR_ANY),
1343                              .imr_ifindex = 0};
1344 #else
1345     struct ip_mreq mreq  = { .imr_multiaddr.s_addr = IPv4MulticastAddress.s_addr,
1346                              .imr_interface = {0}};
1347 #endif
1348
1349     OICStrcpy(endpoint->addr, sizeof(endpoint->addr), IPv4_MULTICAST);
1350     int fd = caglobals.ip.u4.fd;
1351
1352     uint32_t len = u_arraylist_length(iflist);
1353     for (uint32_t i = 0; i < len; i++)
1354     {
1355         CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1356         if (!ifitem)
1357         {
1358             continue;
1359         }
1360         if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
1361         {
1362             continue;
1363         }
1364         if (ifitem->family != AF_INET)
1365         {
1366             continue;
1367         }
1368 #if defined(USE_IP_MREQN)
1369         mreq.imr_ifindex = ifitem->index;
1370 #else
1371         mreq.imr_interface.s_addr = htonl(ifitem->index);
1372 #endif
1373         if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, OPTVAL_T(&mreq), sizeof (mreq)))
1374         {
1375             OIC_LOG_V(ERROR, TAG, "send IP_MULTICAST_IF failed: %s (using defualt)",
1376                     CAIPS_GET_ERROR);
1377         }
1378         sendData(fd, endpoint, data, datalen, "multicast", "ipv4");
1379     }
1380 }
1381
1382 void CAIPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
1383                   bool isMulticast)
1384 {
1385     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
1386     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
1387
1388     bool isSecure = (endpoint->flags & CA_SECURE) != 0;
1389
1390     if (isMulticast)
1391     {
1392         endpoint->port = isSecure ? CA_SECURE_COAP : CA_COAP;
1393
1394         u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
1395         if (!iflist)
1396         {
1397             OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
1398             return;
1399         }
1400
1401         if ((endpoint->flags & CA_IPV6) && caglobals.ip.ipv6enabled)
1402         {
1403             sendMulticastData6(iflist, endpoint, data, datalen);
1404         }
1405         if ((endpoint->flags & CA_IPV4) && caglobals.ip.ipv4enabled)
1406         {
1407             sendMulticastData4(iflist, endpoint, data, datalen);
1408         }
1409
1410         u_arraylist_destroy(iflist);
1411     }
1412     else
1413     {
1414         if (!endpoint->port)    // unicast discovery
1415         {
1416             endpoint->port = isSecure ? CA_SECURE_COAP : CA_COAP;
1417         }
1418
1419         CASocketFd_t fd;
1420         if (caglobals.ip.ipv6enabled && (endpoint->flags & CA_IPV6))
1421         {
1422             fd = isSecure ? caglobals.ip.u6s.fd : caglobals.ip.u6.fd;
1423 #ifndef __WITH_DTLS__
1424             fd = caglobals.ip.u6.fd;
1425 #endif
1426             sendData(fd, endpoint, data, datalen, "unicast", "ipv6");
1427         }
1428         if (caglobals.ip.ipv4enabled && (endpoint->flags & CA_IPV4))
1429         {
1430             fd = isSecure ? caglobals.ip.u4s.fd : caglobals.ip.u4.fd;
1431 #ifndef __WITH_DTLS__
1432             fd = caglobals.ip.u4.fd;
1433 #endif
1434             sendData(fd, endpoint, data, datalen, "unicast", "ipv4");
1435         }
1436     }
1437 }
1438
1439 CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1440 {
1441     VERIFY_NON_NULL(info, TAG, "info is NULL");
1442     VERIFY_NON_NULL(size, TAG, "size is NULL");
1443
1444     u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
1445     if (!iflist)
1446     {
1447         OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
1448         return CA_STATUS_FAILED;
1449     }
1450
1451     uint32_t len = u_arraylist_length(iflist);
1452     uint32_t length = len;
1453
1454 #ifdef __WITH_DTLS__
1455     //If DTLS is supported, each interface can support secure port as well
1456     length = len * 2;
1457 #endif
1458
1459     CAEndpoint_t *eps = (CAEndpoint_t *)OICCalloc(length, sizeof (CAEndpoint_t));
1460     if (!eps)
1461     {
1462         OIC_LOG(ERROR, TAG, "Malloc Failed");
1463         u_arraylist_destroy(iflist);
1464         return CA_MEMORY_ALLOC_FAILED;
1465     }
1466
1467     for (uint32_t i = 0, j = 0; i < len; i++)
1468     {
1469         CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
1470         if(!ifitem)
1471         {
1472             continue;
1473         }
1474
1475         eps[j].adapter = CA_ADAPTER_IP;
1476         eps[j].ifindex = 0;
1477
1478         if (ifitem->family == AF_INET6)
1479         {
1480             eps[j].flags = CA_IPV6;
1481             eps[j].port = caglobals.ip.u6.port;
1482         }
1483         else
1484         {
1485             eps[j].flags = CA_IPV4;
1486             eps[j].port = caglobals.ip.u4.port;
1487         }
1488         OICStrcpy(eps[j].addr, sizeof(eps[j].addr), ifitem->addr);
1489
1490 #ifdef __WITH_DTLS__
1491         j++;
1492
1493         eps[j].adapter = CA_ADAPTER_IP;
1494         eps[j].ifindex = 0;
1495
1496         if (ifitem->family == AF_INET6)
1497         {
1498             eps[j].flags = CA_IPV6 | CA_SECURE;
1499             eps[j].port = caglobals.ip.u6s.port;
1500         }
1501         else
1502         {
1503             eps[j].flags = CA_IPV4 | CA_SECURE;
1504             eps[j].port = caglobals.ip.u4s.port;
1505         }
1506         OICStrcpy(eps[j].addr, sizeof(eps[j].addr), ifitem->addr);
1507 #endif
1508         j++;
1509     }
1510
1511     *info = eps;
1512     *size = length;
1513
1514     u_arraylist_destroy(iflist);
1515
1516     return CA_STATUS_OK;
1517 }
1518
1519 void CAIPSetErrorHandler(CAIPErrorHandleCallback errorHandleCallback)
1520 {
1521     g_ipErrorHandler = errorHandleCallback;
1522 }