Fixed thread safety procedure by adding SOCK_CLOEXEC flag
[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 #include "caipinterface.h"
22
23 #include <sys/types.h>
24 #include <sys/socket.h>
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <sys/select.h>
28 #include <arpa/inet.h>
29 #include <netinet/in.h>
30 #include <errno.h>
31
32 #include "pdu.h"
33 #include "caadapterutils.h"
34 #ifdef __WITH_DTLS__
35 #include "caadapternetdtls.h"
36 #endif
37 #include "camutex.h"
38 #include "oic_malloc.h"
39
40 /**
41  * @def IP_SERVER_TAG
42  * @brief Logging tag for module name
43  */
44 #define IP_SERVER_TAG "IP_SERVER"
45
46 /**
47  * @def CA_UDP_BIND_RETRY_COUNT
48  * @brief Retry count in case of socket bind failure.
49  */
50 #define CA_UDP_BIND_RETRY_COUNT 10
51
52 /**
53  * @def IPNAMESIZE
54  * @brief Max length for ip address.
55  */
56 #define IPNAMESIZE 16
57
58 /**
59  * @def SOCKETOPTION
60  * @brief Socket option.
61  */
62 #define SOCKETOPTION 1
63
64 /**
65  * @var g_packetHandlerStopFlag
66  * @brief Flag for stopping packet handler thread.
67  */
68 static bool g_packetHandlerStopFlag = false;
69
70 /**
71  * @var CAAdapterIPServerContext_t
72  * @brief Thread context information for callbacks and threadpool.
73  */
74 typedef struct
75 {
76     ca_thread_pool_t threadPool;
77     CAIPPacketReceivedCallback packetReceivedCallback;
78     CAIPExceptionCallback exceptionCallback;
79 } CAAdapterIPServerContext_t;
80
81 /**
82  * @var g_serverInfoList
83  * @brief Mutex to synchronize ethenet adapter context.
84  */
85 static u_arraylist_t *g_serverInfoList = NULL;
86
87 /**
88  * @var g_mutexServerInfoList
89  * @brief Mutex to synchronize Server Information.
90  */
91 static ca_mutex g_mutexServerInfoList = NULL;
92
93 /**
94  * @var g_adapterEthServerContext
95  * @brief Mutex to synchronize ethenet adapter context.
96  */
97 static CAAdapterIPServerContext_t *g_adapterEthServerContext = NULL;
98
99 /**
100  * @var g_mutexAdapterServerContext
101  * @brief Mutex to synchronize unicast server
102  */
103 static ca_mutex g_mutexAdapterServerContext = NULL;
104
105 static void CAReceiveHandler(void *data)
106 {
107     OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
108
109     fd_set readFds;
110     int maxSd = 0;
111     struct timeval timeout;
112     char recvBuffer[COAP_MAX_PDU_SIZE] = { 0 };
113
114     while (true != g_packetHandlerStopFlag)
115     {
116         timeout.tv_sec = 1;
117         timeout.tv_usec = 0;
118         FD_ZERO(&readFds);
119
120         ca_mutex_lock(g_mutexServerInfoList);
121         uint32_t listIndex = 0;
122         uint32_t listLength = u_arraylist_length(g_serverInfoList);
123
124         u_arraylist_t *tempServerInfoList = u_arraylist_create();
125         if (!tempServerInfoList)
126         {
127             OIC_LOG(ERROR, IP_SERVER_TAG, "u_arraylist_create failed");
128             ca_mutex_unlock(g_mutexServerInfoList);
129             return;
130         }
131
132         for (listIndex = 0; listIndex < listLength; listIndex++)
133         {
134             CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(g_serverInfoList, listIndex);
135             if (!info)
136             {
137                 listIndex++;
138                 continue;
139             }
140
141             int sd = info->socketFd;
142             //if valid socket descriptor then add to read list
143             if (sd > 0)
144             {
145                 FD_SET(sd, &readFds);
146             }
147
148             //highest file descriptor number, need it for the select function
149             if (sd > maxSd)
150             {
151                 maxSd = sd;
152             }
153
154             CAServerInfo_t *newInfo = (CAServerInfo_t *) OICMalloc(sizeof(CAServerInfo_t));
155             if (!newInfo)
156             {
157                 OIC_LOG(ERROR, IP_SERVER_TAG, "Malloc failed");
158                 CAClearServerInfoList(tempServerInfoList);
159                 ca_mutex_unlock(g_mutexServerInfoList);
160                 return;
161             }
162
163             memcpy(newInfo, info, sizeof(CAServerInfo_t));
164
165             CAResult_t result = u_arraylist_add(tempServerInfoList, (void *) newInfo);
166             if (CA_STATUS_OK != result)
167             {
168                 OIC_LOG(ERROR, IP_SERVER_TAG, "u_arraylist_add failed!Thread exit");
169                 CAClearServerInfoList(tempServerInfoList);
170                 ca_mutex_unlock(g_mutexServerInfoList);
171                 return;
172             }
173         }
174
175         ca_mutex_unlock(g_mutexServerInfoList);
176
177         int ret = select(maxSd + 1, &readFds, NULL, NULL, &timeout);
178         if (g_packetHandlerStopFlag)
179         {
180             OIC_LOG_V(DEBUG, IP_SERVER_TAG,
181                       "Packet receiver handler Stop request received. Thread exited");
182             CAClearServerInfoList(tempServerInfoList);
183             break;
184         }
185         if (ret < 0)
186         {
187             OIC_LOG_V(FATAL, IP_SERVER_TAG, "select returned error %s", strerror(errno));
188             CAClearServerInfoList(tempServerInfoList);
189             continue;
190         }
191
192         listLength = u_arraylist_length(tempServerInfoList);
193         for (listIndex = 0; listIndex < listLength; listIndex++)
194         {
195             CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(tempServerInfoList,
196                                                                       listIndex);
197             if (!info)
198             {
199                 continue;
200             }
201
202             int sd = info->socketFd;
203             if (FD_ISSET(sd , &readFds))
204             {
205                 OIC_LOG_V(ERROR, IP_SERVER_TAG,
206                           "data Received server information ip %s, port %d socket %d",
207                           info->ipAddress, info->port, sd);
208                 memset(recvBuffer, 0, sizeof(recvBuffer));
209
210                 struct sockaddr_in srcSockAddress = { 0 };
211                 socklen_t srcAddressLen = sizeof(srcSockAddress);
212
213                 //Reading from socket
214                 ssize_t recvLen = recvfrom(sd, recvBuffer, sizeof(recvBuffer), 0,
215                                            (struct sockaddr *) &srcSockAddress, &srcAddressLen);
216                 if (-1 == recvLen)
217                 {
218                     OIC_LOG_V(ERROR, IP_SERVER_TAG, "Recvfrom failed %s", strerror(errno));
219                     continue;
220                 }
221                 else if (0 == recvLen)
222                 {
223                     OIC_LOG_V(ERROR, IP_SERVER_TAG, "Server socket shutdown sock fd[%d]", sd);
224                     ca_mutex_lock(g_mutexAdapterServerContext);
225                     // Notify upper layer this exception
226                     if (g_adapterEthServerContext->exceptionCallback)
227                     {
228                         // need to make proper exception callback.
229                         //g_adapterEthServerContext->exceptionCallback(ctx->type);
230                     }
231                     ca_mutex_unlock(g_mutexAdapterServerContext);
232                 }
233
234                 char srcIPAddress[CA_IPADDR_SIZE] = { 0 };
235                 if (!inet_ntop(AF_INET, &srcSockAddress.sin_addr.s_addr, srcIPAddress,
236                                sizeof(srcIPAddress)))
237                 {
238
239                     OIC_LOG(ERROR, IP_SERVER_TAG, "inet_ntop is failed!");
240                     continue;
241                 }
242
243                 uint16_t srcPort = ntohs(srcSockAddress.sin_port);
244
245                 OIC_LOG_V(DEBUG, IP_SERVER_TAG, "Received packet from %s:%d len %d",
246                           srcIPAddress, srcPort, recvLen);
247
248                 char *netMask = NULL;
249                 if (CA_STATUS_OK != CAIPGetInterfaceSubnetMask(info->ifAddr, &netMask))
250                 {
251                     OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to get IP subnet");
252                     continue;
253                 }
254
255                 if (!CAAdapterIsSameSubnet(info->ifAddr, srcIPAddress, netMask))
256                 {
257                     OIC_LOG(DEBUG, IP_SERVER_TAG,
258                             "Packet received from different subnet, Ignore!");
259                     OICFree(netMask);
260                     continue;
261                 }
262                 OICFree(netMask);
263
264                 if (info->isSecured)
265                 {
266 #ifdef __WITH_DTLS__
267                     CAResult_t ret = CAAdapterNetDtlsDecrypt(srcIPAddress, srcPort,
268                                                              (uint8_t *)recvBuffer, recvLen,
269                                                              DTLS_IP);
270                     OIC_LOG_V(DEBUG, IP_SERVER_TAG,
271                               "CAAdapterNetDtlsDecrypt returns [%d]", ret);
272 #endif
273                 }
274                 else //both multicast and unicast
275                 {
276                     ca_mutex_lock(g_mutexAdapterServerContext);
277
278                     if (g_adapterEthServerContext->packetReceivedCallback)
279                     {
280                         g_adapterEthServerContext->packetReceivedCallback(srcIPAddress, srcPort,
281                                                                           recvBuffer, recvLen,
282                                                                           false);
283                     }
284
285                     ca_mutex_unlock(g_mutexAdapterServerContext);
286                 }
287             }
288         }
289         CAClearServerInfoList(tempServerInfoList);
290     }
291     OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
292 }
293
294 static CAResult_t CACreateSocket(int *socketFD, const char *localIp, uint16_t *port,
295                                  bool forceBindStart)
296 {
297     VERIFY_NON_NULL(socketFD, IP_SERVER_TAG, "socketFD is NULL");
298     VERIFY_NON_NULL(localIp, IP_SERVER_TAG, "localIp is NULL");
299     VERIFY_NON_NULL(port, IP_SERVER_TAG, "port is NULL");
300     // Create a UDP socket
301     int sock = -1;
302
303 #ifdef SOCK_CLOEXEC
304     sock = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
305 #endif
306
307     if (-1 == sock)
308     {
309         sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
310     }
311
312     if (-1 == sock)
313     {
314         OIC_LOG_V(ERROR, IP_SERVER_TAG, "Failed to create Socket, Error code: %s",
315                   strerror(errno));
316         return CA_STATUS_FAILED;
317     }
318
319     // Make the socket non-blocking
320     if (-1 == fcntl(sock, F_SETFL, O_NONBLOCK))
321     {
322         OIC_LOG_V(ERROR, IP_SERVER_TAG, "Failed to set non-block mode, Error code: %s",
323                   strerror(errno));
324
325         close(sock);
326         return CA_STATUS_FAILED;
327     }
328
329     if (true == forceBindStart)
330     {
331         int setOptionOn = SOCKETOPTION;
332         if (-1 == setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &setOptionOn,
333                              sizeof(setOptionOn)))
334         {
335             OIC_LOG_V(ERROR, IP_SERVER_TAG, "Failed to set SO_REUSEADDR! Error code: %s",
336                       strerror(errno));
337             close(sock);
338             return CA_STATUS_FAILED;
339         }
340     }
341
342     struct sockaddr_in sockAddr = { 0 };
343     uint16_t serverPort = *port;
344     sockAddr.sin_family = AF_INET;
345     sockAddr.sin_port = htons(serverPort);
346     if (localIp)
347     {
348         sockAddr.sin_addr.s_addr = inet_addr(localIp);
349     }
350     else
351     {
352         sockAddr.sin_addr.s_addr = htonl(INADDR_ANY);
353     }
354
355     int16_t i = 0;
356     bool isBound = false;
357     for (i = 0; i < CA_UDP_BIND_RETRY_COUNT; i++)
358     {
359         if (-1 == bind(sock, (struct sockaddr *) &sockAddr, sizeof(sockAddr)))
360         {
361             if (false == forceBindStart)
362             {
363                 OIC_LOG_V(ERROR, IP_SERVER_TAG, "Failed to bind socket[%s]. Trying again..",
364                           strerror(errno));
365
366                 //Set the port to next one
367                 serverPort += 1;
368                 sockAddr.sin_port = htons(serverPort);
369                 continue;
370             }
371             else
372             {
373                 OIC_LOG_V(ERROR, IP_SERVER_TAG, "Failed to bind socket[%s]!",
374                           strerror(errno));
375                 break;
376             }
377         }
378
379         isBound = true;
380         break;
381     }
382
383     if (false == isBound)
384     {
385         close(sock);
386         return CA_STATUS_FAILED;
387     }
388
389     *port = serverPort;
390     *socketFD = sock;
391     return CA_STATUS_OK;
392 }
393
394 static void CACloseSocket(int socketFD)
395 {
396     if (-1 == socketFD)
397     {
398         OIC_LOG(ERROR, IP_SERVER_TAG, "Invalid Socket Fd");
399         return;
400     }
401
402     // close the socket
403     if (-1 == close(socketFD))
404     {
405         OIC_LOG_V(ERROR, IP_SERVER_TAG, "Failed to close the socket, Error code: %s\n",
406                   strerror(errno));
407     }
408 }
409
410 static CAResult_t CAStartUnicastServer(const char *localAddress, uint16_t *port,
411                                        bool forceBindStart, bool isSecured, int *serverFD)
412 {
413     OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
414
415     VERIFY_NON_NULL(serverFD, IP_SERVER_TAG, "serverFD");
416     VERIFY_NON_NULL(localAddress, IP_SERVER_TAG, "localAddress");
417     VERIFY_NON_NULL(port, IP_SERVER_TAG, "port");
418
419     CAResult_t ret = CACreateSocket(serverFD, localAddress, port, forceBindStart);
420     if (CA_STATUS_OK != ret)
421     {
422         OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to create unicast socket");
423     }
424
425     OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
426     return ret;
427 }
428
429 static CAResult_t CAIPStartPacketReceiverHandler()
430 {
431     OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
432
433     ca_mutex_lock(g_mutexServerInfoList);
434
435     uint32_t listLength = u_arraylist_length(g_serverInfoList);
436
437     ca_mutex_unlock(g_mutexServerInfoList);
438
439     ca_mutex_lock(g_mutexAdapterServerContext);
440
441     if (!g_adapterEthServerContext)
442     {
443         OIC_LOG(ERROR, IP_SERVER_TAG, "g_adapterEthServerContext NULL");
444         ca_mutex_unlock(g_mutexAdapterServerContext);
445         return CA_STATUS_FAILED;
446     }
447
448     if (1 == listLength) //Its first time.
449     {
450         if (CA_STATUS_OK != ca_thread_pool_add_task(g_adapterEthServerContext->threadPool,
451                                                    CAReceiveHandler, NULL ))
452         {
453             OIC_LOG(ERROR, IP_SERVER_TAG, "thread_pool_add_task failed!");
454             ca_mutex_unlock(g_mutexAdapterServerContext);
455             return CA_STATUS_FAILED;
456         }
457         OIC_LOG(DEBUG, IP_SERVER_TAG, "CAReceiveHandler thread started successfully.");
458     }
459     else
460     {
461         OIC_LOG(DEBUG, IP_SERVER_TAG, "CAReceiveHandler thread already is running");
462     }
463     ca_mutex_unlock(g_mutexAdapterServerContext);
464
465     OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
466
467     return CA_STATUS_OK;
468 }
469
470 static void CAIPServerDestroyMutex(void)
471 {
472     OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
473
474     if (g_mutexServerInfoList)
475     {
476         ca_mutex_free(g_mutexServerInfoList);
477         g_mutexServerInfoList = NULL;
478     }
479
480     if (g_mutexAdapterServerContext)
481     {
482         ca_mutex_free(g_mutexAdapterServerContext);
483         g_mutexAdapterServerContext = NULL;
484     }
485
486     OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
487 }
488
489 static CAResult_t CAIPServerCreateMutex(void)
490 {
491     OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
492
493     g_mutexServerInfoList = ca_mutex_new();
494     if (!g_mutexServerInfoList)
495     {
496         OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
497         return CA_MEMORY_ALLOC_FAILED;
498     }
499
500     g_mutexAdapterServerContext = ca_mutex_new();
501     if (!g_mutexAdapterServerContext)
502     {
503         OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to created mutex!");
504         ca_mutex_free(g_mutexServerInfoList);
505         g_mutexServerInfoList = NULL;
506         return CA_MEMORY_ALLOC_FAILED;
507     }
508
509     OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
510     return CA_STATUS_OK;
511 }
512
513 CAResult_t CAIPInitializeServer(const ca_thread_pool_t threadPool)
514 {
515     OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
516
517     // Input validation
518     VERIFY_NON_NULL(threadPool, IP_SERVER_TAG, "Thread pool handle is NULL");
519
520     // Initialize mutex
521     if (CA_STATUS_OK != CAIPServerCreateMutex())
522     {
523         OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to create mutex!");
524         return CA_STATUS_FAILED;
525     }
526
527     ca_mutex_lock(g_mutexAdapterServerContext);
528     g_adapterEthServerContext = (CAAdapterIPServerContext_t *) OICCalloc(1,
529                                  sizeof(CAAdapterIPServerContext_t));
530
531     if (!g_adapterEthServerContext)
532     {
533         OIC_LOG(ERROR, IP_SERVER_TAG, "Malloc failed");
534         ca_mutex_unlock(g_mutexAdapterServerContext);
535         return CA_MEMORY_ALLOC_FAILED;
536     }
537
538     g_adapterEthServerContext->threadPool = threadPool;
539
540     ca_mutex_unlock(g_mutexAdapterServerContext);
541
542     ca_mutex_lock(g_mutexServerInfoList);
543
544     g_serverInfoList = u_arraylist_create();
545     if (!g_serverInfoList)
546     {
547         OIC_LOG(ERROR, IP_SERVER_TAG, "u_arraylist_create failed");
548         ca_mutex_unlock(g_mutexServerInfoList);
549         return CA_MEMORY_ALLOC_FAILED;
550     }
551     ca_mutex_unlock(g_mutexServerInfoList);
552     OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
553     return CA_STATUS_OK;
554 }
555
556 void CAIPTerminateServer()
557 {
558     OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
559     ca_mutex_lock(g_mutexAdapterServerContext);
560     if (!g_adapterEthServerContext)
561     {
562         OIC_LOG(ERROR, IP_SERVER_TAG, "g_adapterEthServerContext NULL");
563         ca_mutex_unlock(g_mutexAdapterServerContext);
564         return;
565     }
566
567     OICFree(g_adapterEthServerContext);
568     g_adapterEthServerContext = NULL;
569
570     ca_mutex_unlock(g_mutexAdapterServerContext);
571
572     ca_mutex_lock(g_mutexServerInfoList);
573
574     CAClearServerInfoList(g_serverInfoList);
575     g_serverInfoList = NULL;
576
577     ca_mutex_unlock(g_mutexServerInfoList);
578     // Destroy mutex
579     CAIPServerDestroyMutex();
580
581     OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
582
583 }
584
585 CAResult_t CAIPStartUnicastServer(const char *localAddress, uint16_t *port,
586                                         bool forceBindStart, bool isSecured)
587 {
588     OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
589
590     // Input validation
591     VERIFY_NON_NULL(localAddress, IP_SERVER_TAG, "localAddress");
592     VERIFY_NON_NULL(port, IP_SERVER_TAG, "port");
593
594     if (0 >= *port)
595     {
596         OIC_LOG(ERROR, IP_SERVER_TAG, "Invalid input: port is invalid!");
597         return CA_STATUS_INVALID_PARAM;
598     }
599
600     ca_mutex_lock(g_mutexServerInfoList);
601     bool isUnicastServerStarted = CAIsUnicastServerStarted(g_serverInfoList, localAddress, *port);
602     if (!isUnicastServerStarted)
603     {
604         int unicastServerFd = -1;
605         if (CA_STATUS_OK != CAStartUnicastServer(localAddress, port, forceBindStart, isSecured,
606                                                  &unicastServerFd))
607         {
608             OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to start unicast server!");
609             ca_mutex_unlock(g_mutexServerInfoList);
610             return CA_STATUS_FAILED;
611         }
612
613         CAServerInfo_t *info = (CAServerInfo_t *) OICCalloc(1, sizeof(CAServerInfo_t));
614         if (!info)
615         {
616             OIC_LOG(ERROR, IP_SERVER_TAG, "Malloc failed");
617             close(unicastServerFd);
618             ca_mutex_unlock(g_mutexServerInfoList);
619             return CA_MEMORY_ALLOC_FAILED;
620         }
621
622         char *netMask = NULL;
623         if (CA_STATUS_OK != CAIPGetInterfaceSubnetMask(localAddress, &netMask))
624         {
625             OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to get IP subnet");
626         }
627         if (netMask)
628         {
629             strncpy(info->subNetMask, netMask, strlen(netMask));
630             OICFree(netMask);
631         }
632         strncpy(info->ipAddress, localAddress, strlen(localAddress));
633         info->port = *port;
634         info->socketFd = unicastServerFd;
635         info->isSecured = isSecured;
636         info->isServerStarted = true;
637         info->isMulticastServer = false;
638         strncpy(info->ifAddr, localAddress, strlen(localAddress));
639
640         CAResult_t res = CAAddServerInfo(g_serverInfoList, info);
641         if (CA_STATUS_OK != res)
642         {
643             OIC_LOG(ERROR, IP_SERVER_TAG, "CAAddServerInfo failed!");
644             close(unicastServerFd);
645             ca_mutex_unlock(g_mutexServerInfoList);
646             return res;
647         }
648         ca_mutex_unlock(g_mutexServerInfoList);
649
650         res = CAIPStartPacketReceiverHandler();
651         if (CA_STATUS_OK != res)
652         {
653             OIC_LOG(ERROR, IP_SERVER_TAG, "CAIPStartPacketReceiverHandler failed!");
654             close(unicastServerFd);
655             return res;
656         }
657     }
658     else
659     {
660         OIC_LOG_V(DEBUG, IP_SERVER_TAG, "Already Unicast Server Started ip [%s] port [%d]",
661                   localAddress, *port);
662         ca_mutex_unlock(g_mutexServerInfoList);
663     }
664
665     OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
666     return CA_STATUS_OK;
667 }
668
669 CAResult_t CAIPStartMulticastServer(const char *localAddress, const char *multicastAddress,
670                                           uint16_t multicastPort)
671 {
672     OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
673
674     // Input validation
675     VERIFY_NON_NULL(localAddress, IP_SERVER_TAG, "localAddress");
676     VERIFY_NON_NULL(multicastAddress, IP_SERVER_TAG, "port");
677
678     uint16_t port = multicastPort;
679     if (0 >= port)
680     {
681         OIC_LOG(ERROR, IP_SERVER_TAG, "Invalid input: Multicast port is invalid!");
682         return CA_STATUS_INVALID_PARAM;
683     }
684
685     ca_mutex_lock(g_mutexServerInfoList);
686     bool isMulticastServerStarted = CAIsMulticastServerStarted(g_serverInfoList, localAddress,
687                                                                multicastAddress, port);
688     if (!isMulticastServerStarted)
689     {
690         int mulicastServerFd = -1;
691         CAResult_t ret = CACreateSocket(&mulicastServerFd, multicastAddress, &port, true);
692         if (ret != CA_STATUS_OK)
693         {
694             OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to create multicast socket");
695             ca_mutex_unlock(g_mutexServerInfoList);
696             return ret;
697         }
698
699         struct ip_mreq multicastMemberReq = {.imr_interface.s_addr = inet_addr(localAddress)};
700         inet_aton(multicastAddress, &multicastMemberReq.imr_multiaddr);
701
702         if (-1 == setsockopt(mulicastServerFd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
703                              (char *) &multicastMemberReq, sizeof(struct ip_mreq)))
704         {
705             OIC_LOG_V(ERROR, IP_SERVER_TAG,
706                       "Failed to add to multicast group, Error code: %s\n", strerror(errno));
707             close(mulicastServerFd);
708             ca_mutex_unlock(g_mutexServerInfoList);
709             return CA_STATUS_FAILED;
710         }
711
712         CAServerInfo_t *info = (CAServerInfo_t *) OICCalloc(1, sizeof(CAServerInfo_t));
713         if (!info)
714         {
715             OIC_LOG(ERROR, IP_SERVER_TAG, "Malloc failed");
716             close(mulicastServerFd);
717             ca_mutex_unlock(g_mutexServerInfoList);
718             return CA_MEMORY_ALLOC_FAILED;
719         }
720
721         char *netMask = NULL;
722         if (CA_STATUS_OK != CAIPGetInterfaceSubnetMask(localAddress, &netMask))
723         {
724             OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to get IP subnet");
725         }
726         if (netMask)
727         {
728             strncpy(info->subNetMask, netMask, strlen(netMask));
729             OICFree(netMask);
730         }
731
732         strncpy(info->ipAddress, multicastAddress, strlen(multicastAddress));
733         info->port = multicastPort;
734         info->socketFd = mulicastServerFd;
735         info->isSecured = false;
736         info->isServerStarted = true;
737         info->isMulticastServer = true;
738         strncpy(info->ifAddr, localAddress, strlen(localAddress));
739
740         ret = CAAddServerInfo(g_serverInfoList, info);
741
742         if (CA_STATUS_OK != ret)
743         {
744             OIC_LOG(ERROR, IP_SERVER_TAG, "CAAddServerInfo failed!");
745             close(mulicastServerFd);
746             ca_mutex_unlock(g_mutexServerInfoList);
747             return ret;
748         }
749         ca_mutex_unlock(g_mutexServerInfoList);
750
751         ret = CAIPStartPacketReceiverHandler();
752         if (CA_STATUS_OK != ret)
753         {
754             OIC_LOG(ERROR, IP_SERVER_TAG, "CAIPStartPacketReceiverHandler failed!");
755             close(mulicastServerFd);
756             return ret;
757         }
758     }
759     else
760     {
761         OIC_LOG_V(DEBUG, IP_SERVER_TAG,
762                   "Multicast Server is already started on interface addr[%s]", localAddress);
763         ca_mutex_unlock(g_mutexServerInfoList);
764     }
765
766     OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
767     return CA_STATUS_OK;
768 }
769
770 CAResult_t CAIPStopServer(const char *interfaceAddress)
771 {
772     OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
773
774     VERIFY_NON_NULL(interfaceAddress, IP_SERVER_TAG, "interfaceAddress is NULL");
775
776     ca_mutex_lock(g_mutexServerInfoList);
777     uint32_t listIndex = 0;
778     uint32_t listLength = u_arraylist_length(g_serverInfoList);
779
780     for (listIndex = 0; listIndex < listLength;)
781     {
782         CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(g_serverInfoList, listIndex);
783         if (!info)
784         {
785             listIndex++;
786             continue;
787         }
788
789         if (info->isMulticastServer && strncmp(interfaceAddress, info->ifAddr, strlen(info->ifAddr))
790                 == 0)
791         {
792             if (u_arraylist_remove(g_serverInfoList, listIndex))
793             {
794                 struct ip_mreq multicastMemberReq = { { 0 }, { 0 } };
795
796                 multicastMemberReq.imr_interface.s_addr = inet_addr(info->ifAddr);
797                 inet_aton(info->ipAddress, &multicastMemberReq.imr_multiaddr);
798                 if (-1 == setsockopt(info->socketFd, IPPROTO_IP, IP_DROP_MEMBERSHIP,
799                                      (char *) &multicastMemberReq, sizeof(struct ip_mreq)))
800                 {
801                     OIC_LOG_V(ERROR, IP_SERVER_TAG,
802                               "Failed to leave multicast group, Error code: %s", strerror(errno));
803                 }
804                 CACloseSocket(info->socketFd);
805                 OICFree(info);
806                 OIC_LOG_V(DEBUG, IP_SERVER_TAG,
807                           "Multicast server is stopped successfully on IF [%s]", info->ifAddr);
808                 // Reduce list length by 1 as we removed one element.
809                 listLength--;
810             }
811             else
812             {
813                 OIC_LOG(ERROR, IP_SERVER_TAG, "u_arraylist_remove failed.");
814                 ca_mutex_unlock(g_mutexServerInfoList);
815                 return CA_STATUS_FAILED;
816             }
817         }
818         else if (strncmp(interfaceAddress, info->ipAddress, strlen(info->ipAddress)) == 0)
819         {
820             if (u_arraylist_remove(g_serverInfoList, listIndex))
821             {
822                 CACloseSocket(info->socketFd);
823                 OICFree(info);
824                 OIC_LOG_V(DEBUG, IP_SERVER_TAG,
825                           "Unicast server is stopped successfully on IF [%s]", info->ifAddr);
826                 // Reduce list length by 1 as we removed one element.
827                 listLength--;
828             }
829             else
830             {
831                 OIC_LOG(ERROR, IP_SERVER_TAG, "u_arraylist_remove failed.");
832                 ca_mutex_unlock(g_mutexServerInfoList);
833                 return CA_STATUS_FAILED;
834             }
835         }
836         else
837         {
838             listIndex++;
839         }
840     }
841
842     OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
843     ca_mutex_unlock(g_mutexServerInfoList);
844     return CA_STATUS_OK;
845 }
846
847 CAResult_t CAIPStopAllServers()
848 {
849     OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
850
851     g_packetHandlerStopFlag = true;
852
853     ca_mutex_lock(g_mutexServerInfoList);
854
855     uint32_t listIndex = 0;
856     uint32_t listLength = u_arraylist_length(g_serverInfoList);
857     for (listIndex = 0; listIndex < listLength;)
858     {
859         CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(g_serverInfoList, listIndex);
860         if (!info)
861         {
862             listIndex++;
863             continue;
864         }
865         if (u_arraylist_remove(g_serverInfoList, listIndex))
866         {
867             if (info->isMulticastServer)
868             {
869                 struct ip_mreq multicastMemberReq = { { 0 }, { 0 } };
870
871                 multicastMemberReq.imr_interface.s_addr = inet_addr(info->ifAddr);
872                 inet_aton(info->ipAddress, &multicastMemberReq.imr_multiaddr);
873                 if (-1 == setsockopt(info->socketFd, IPPROTO_IP, IP_DROP_MEMBERSHIP,
874                                      (char *) &multicastMemberReq, sizeof(struct ip_mreq)))
875                 {
876                     OIC_LOG_V(ERROR, IP_SERVER_TAG,
877                               "Failed to leave multicast group, Error code: %s", strerror(errno));
878                 }
879             }
880             CACloseSocket(info->socketFd);
881             //Freeing server info.
882             OICFree(info);
883             // Reduce list length by 1 as we removed one element.
884             listLength--;
885         }
886         else
887         {
888             OIC_LOG(ERROR, IP_SERVER_TAG, "u_arraylist_remove failed.");
889             ca_mutex_unlock(g_mutexServerInfoList);
890             return CA_STATUS_FAILED;
891         }
892     }
893
894     ca_mutex_unlock(g_mutexServerInfoList);
895
896     OIC_LOG(DEBUG, IP_SERVER_TAG, "All Server stopped successfully. OUT");
897     return CA_STATUS_OK;
898 }
899
900 uint16_t CAGetServerPortNum(const char *ipAddress, bool isSecured)
901 {
902     ca_mutex_lock(g_mutexServerInfoList);
903
904     uint16_t port = CAGetServerPort(g_serverInfoList, ipAddress, isSecured);
905
906     ca_mutex_unlock(g_mutexServerInfoList);
907
908     return port;
909 }
910
911 CAResult_t CAGetIPServerInfoList(u_arraylist_t **serverInfoList)
912 {
913     OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
914     ca_mutex_lock(g_mutexServerInfoList);
915
916     uint32_t list_index = 0;
917     uint32_t list_length = u_arraylist_length(g_serverInfoList);
918     for (list_index = 0; list_index < list_length; list_index++)
919     {
920         CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(g_serverInfoList, list_index);
921         if (!info)
922         {
923             continue;
924         }
925
926         CAServerInfo_t *newNetinfo = (CAServerInfo_t *) OICMalloc(sizeof(CAServerInfo_t));
927         if (!newNetinfo)
928         {
929             OIC_LOG(ERROR, IP_SERVER_TAG, "Malloc failed!");
930             ca_mutex_unlock(g_mutexServerInfoList);
931             return CA_MEMORY_ALLOC_FAILED;
932         }
933
934         memcpy(newNetinfo, info, sizeof(*info));
935
936         CAResult_t result = u_arraylist_add(*serverInfoList, (void *) newNetinfo);
937         if (CA_STATUS_OK != result)
938         {
939             OIC_LOG(ERROR, IP_SERVER_TAG, "u_arraylist_add failed!");
940             ca_mutex_unlock(g_mutexServerInfoList);
941             return CA_STATUS_FAILED;
942         }
943     }
944     ca_mutex_unlock(g_mutexServerInfoList);
945     OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
946     return CA_STATUS_OK;
947 }
948
949 void CAIPSetPacketReceiveCallback(CAIPPacketReceivedCallback callback)
950 {
951     OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
952
953     ca_mutex_lock(g_mutexAdapterServerContext);
954
955     if (!g_adapterEthServerContext)
956     {
957         OIC_LOG(ERROR, IP_SERVER_TAG, "g_adapterEthServerContext NULL");
958         ca_mutex_unlock(g_mutexAdapterServerContext);
959         return;
960     }
961     g_adapterEthServerContext->packetReceivedCallback = callback;
962
963     ca_mutex_unlock(g_mutexAdapterServerContext);
964
965     OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
966 }
967
968 void CAIPSetExceptionCallback(CAIPExceptionCallback callback)
969 {
970     OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
971     ca_mutex_lock(g_mutexAdapterServerContext);
972
973     if (!g_adapterEthServerContext)
974     {
975         OIC_LOG(ERROR, IP_SERVER_TAG, "g_adapterEthServerContext NULL");
976         ca_mutex_unlock(g_mutexAdapterServerContext);
977         return;
978     }
979     g_adapterEthServerContext->exceptionCallback = callback;
980
981     ca_mutex_unlock(g_mutexAdapterServerContext);
982
983     OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
984 }
985