Imported Upstream version 0.9.1
[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
351     int16_t i = 0;
352     bool isBound = false;
353     for (i = 0; i < CA_UDP_BIND_RETRY_COUNT; i++)
354     {
355         if (-1 == bind(sock, (struct sockaddr *) &sockAddr, sizeof(sockAddr)))
356         {
357             if (false == forceBindStart)
358             {
359                 OIC_LOG_V(ERROR, IP_SERVER_TAG, "Failed to bind socket[%s]. Trying again..",
360                           strerror(errno));
361
362                 //Set the port to next one
363                 serverPort += 1;
364                 sockAddr.sin_port = htons(serverPort);
365                 continue;
366             }
367             else
368             {
369                 OIC_LOG_V(ERROR, IP_SERVER_TAG, "Failed to bind socket[%s]!",
370                           strerror(errno));
371                 break;
372             }
373         }
374
375         isBound = true;
376         break;
377     }
378
379     if (false == isBound)
380     {
381         close(sock);
382         return CA_STATUS_FAILED;
383     }
384
385     *port = serverPort;
386     *socketFD = sock;
387     return CA_STATUS_OK;
388 }
389
390 static void CACloseSocket(int socketFD)
391 {
392     if (-1 == socketFD)
393     {
394         OIC_LOG(ERROR, IP_SERVER_TAG, "Invalid Socket Fd");
395         return;
396     }
397
398     // close the socket
399     if (-1 == close(socketFD))
400     {
401         OIC_LOG_V(ERROR, IP_SERVER_TAG, "Failed to close the socket, Error code: %s\n",
402                   strerror(errno));
403     }
404 }
405
406 static CAResult_t CAStartUnicastServer(const char *localAddress, uint16_t *port,
407                                        bool forceBindStart, bool isSecured, int *serverFD)
408 {
409     OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
410
411     VERIFY_NON_NULL(serverFD, IP_SERVER_TAG, "serverFD");
412     VERIFY_NON_NULL(localAddress, IP_SERVER_TAG, "localAddress");
413     VERIFY_NON_NULL(port, IP_SERVER_TAG, "port");
414
415     CAResult_t ret = CACreateSocket(serverFD, localAddress, port, forceBindStart);
416     if (CA_STATUS_OK != ret)
417     {
418         OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to create unicast socket");
419     }
420
421     OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
422     return ret;
423 }
424
425 static CAResult_t CAIPStartPacketReceiverHandler()
426 {
427     OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
428
429     ca_mutex_lock(g_mutexServerInfoList);
430
431     uint32_t listLength = u_arraylist_length(g_serverInfoList);
432
433     ca_mutex_unlock(g_mutexServerInfoList);
434
435     ca_mutex_lock(g_mutexAdapterServerContext);
436
437     if (!g_adapterEthServerContext)
438     {
439         OIC_LOG(ERROR, IP_SERVER_TAG, "g_adapterEthServerContext NULL");
440         ca_mutex_unlock(g_mutexAdapterServerContext);
441         return CA_STATUS_FAILED;
442     }
443
444     if (1 == listLength) //Its first time.
445     {
446         g_packetHandlerStopFlag = false;
447         if (CA_STATUS_OK != ca_thread_pool_add_task(g_adapterEthServerContext->threadPool,
448                                                    CAReceiveHandler, NULL ))
449         {
450             OIC_LOG(ERROR, IP_SERVER_TAG, "thread_pool_add_task failed!");
451             ca_mutex_unlock(g_mutexAdapterServerContext);
452             return CA_STATUS_FAILED;
453         }
454         OIC_LOG(DEBUG, IP_SERVER_TAG, "CAReceiveHandler thread started successfully.");
455     }
456     else
457     {
458         OIC_LOG(DEBUG, IP_SERVER_TAG, "CAReceiveHandler thread already is running");
459     }
460     ca_mutex_unlock(g_mutexAdapterServerContext);
461
462     OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
463
464     return CA_STATUS_OK;
465 }
466
467 static void CAIPServerDestroyMutex(void)
468 {
469     OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
470
471     if (g_mutexServerInfoList)
472     {
473         ca_mutex_free(g_mutexServerInfoList);
474         g_mutexServerInfoList = NULL;
475     }
476
477     if (g_mutexAdapterServerContext)
478     {
479         ca_mutex_free(g_mutexAdapterServerContext);
480         g_mutexAdapterServerContext = NULL;
481     }
482
483     OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
484 }
485
486 static CAResult_t CAIPServerCreateMutex(void)
487 {
488     OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
489
490     g_mutexServerInfoList = ca_mutex_new();
491     if (!g_mutexServerInfoList)
492     {
493         OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
494         return CA_MEMORY_ALLOC_FAILED;
495     }
496
497     g_mutexAdapterServerContext = ca_mutex_new();
498     if (!g_mutexAdapterServerContext)
499     {
500         OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to created mutex!");
501         ca_mutex_free(g_mutexServerInfoList);
502         g_mutexServerInfoList = NULL;
503         return CA_MEMORY_ALLOC_FAILED;
504     }
505
506     OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
507     return CA_STATUS_OK;
508 }
509
510 CAResult_t CAIPInitializeServer(const ca_thread_pool_t threadPool)
511 {
512     OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
513
514     // Input validation
515     VERIFY_NON_NULL(threadPool, IP_SERVER_TAG, "Thread pool handle is NULL");
516
517     // Initialize mutex
518     if (CA_STATUS_OK != CAIPServerCreateMutex())
519     {
520         OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to create mutex!");
521         return CA_STATUS_FAILED;
522     }
523
524     ca_mutex_lock(g_mutexAdapterServerContext);
525     g_adapterEthServerContext = (CAAdapterIPServerContext_t *) OICCalloc(1,
526                                  sizeof(CAAdapterIPServerContext_t));
527
528     if (!g_adapterEthServerContext)
529     {
530         OIC_LOG(ERROR, IP_SERVER_TAG, "Malloc failed");
531         ca_mutex_unlock(g_mutexAdapterServerContext);
532         return CA_MEMORY_ALLOC_FAILED;
533     }
534
535     g_adapterEthServerContext->threadPool = threadPool;
536
537     ca_mutex_unlock(g_mutexAdapterServerContext);
538
539     ca_mutex_lock(g_mutexServerInfoList);
540
541     g_serverInfoList = u_arraylist_create();
542     if (!g_serverInfoList)
543     {
544         OIC_LOG(ERROR, IP_SERVER_TAG, "u_arraylist_create failed");
545         ca_mutex_unlock(g_mutexServerInfoList);
546         return CA_MEMORY_ALLOC_FAILED;
547     }
548     ca_mutex_unlock(g_mutexServerInfoList);
549     OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
550     return CA_STATUS_OK;
551 }
552
553 void CAIPTerminateServer()
554 {
555     OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
556     ca_mutex_lock(g_mutexAdapterServerContext);
557     if (!g_adapterEthServerContext)
558     {
559         OIC_LOG(ERROR, IP_SERVER_TAG, "g_adapterEthServerContext NULL");
560         ca_mutex_unlock(g_mutexAdapterServerContext);
561         return;
562     }
563
564     OICFree(g_adapterEthServerContext);
565     g_adapterEthServerContext = NULL;
566
567     ca_mutex_unlock(g_mutexAdapterServerContext);
568
569     ca_mutex_lock(g_mutexServerInfoList);
570
571     CAClearServerInfoList(g_serverInfoList);
572     g_serverInfoList = NULL;
573
574     ca_mutex_unlock(g_mutexServerInfoList);
575     // Destroy mutex
576     CAIPServerDestroyMutex();
577
578     OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
579
580 }
581
582 CAResult_t CAIPStartUnicastServer(const char *localAddress, uint16_t *port,
583                                         bool forceBindStart, bool isSecured)
584 {
585     OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
586
587     // Input validation
588     VERIFY_NON_NULL(localAddress, IP_SERVER_TAG, "localAddress");
589     VERIFY_NON_NULL(port, IP_SERVER_TAG, "port");
590
591     if (0 >= *port)
592     {
593         OIC_LOG(ERROR, IP_SERVER_TAG, "Invalid input: port is invalid!");
594         return CA_STATUS_INVALID_PARAM;
595     }
596
597     ca_mutex_lock(g_mutexServerInfoList);
598     bool isUnicastServerStarted = CAIsUnicastServerStarted(g_serverInfoList, localAddress, *port);
599     if (!isUnicastServerStarted)
600     {
601         int unicastServerFd = -1;
602         if (CA_STATUS_OK != CAStartUnicastServer(localAddress, port, forceBindStart, isSecured,
603                                                  &unicastServerFd))
604         {
605             OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to start unicast server!");
606             ca_mutex_unlock(g_mutexServerInfoList);
607             return CA_STATUS_FAILED;
608         }
609
610         CAServerInfo_t *info = (CAServerInfo_t *) OICCalloc(1, sizeof(CAServerInfo_t));
611         if (!info)
612         {
613             OIC_LOG(ERROR, IP_SERVER_TAG, "Malloc failed");
614             close(unicastServerFd);
615             ca_mutex_unlock(g_mutexServerInfoList);
616             return CA_MEMORY_ALLOC_FAILED;
617         }
618
619         char *netMask = NULL;
620         if (CA_STATUS_OK != CAIPGetInterfaceSubnetMask(localAddress, &netMask))
621         {
622             OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to get IP subnet");
623         }
624         if (netMask)
625         {
626             strncpy(info->subNetMask, netMask, sizeof(info->subNetMask) - 1);
627             info->subNetMask[sizeof(info->subNetMask)-1] = '\0';
628             OICFree(netMask);
629         }
630         strncpy(info->ipAddress, localAddress, sizeof(info->ipAddress) - 1);
631         info->ipAddress[sizeof(info->ipAddress) - 1] = '\0';
632         info->port = *port;
633         info->socketFd = unicastServerFd;
634         info->isSecured = isSecured;
635         info->isServerStarted = true;
636         info->isMulticastServer = false;
637         strncpy(info->ifAddr, localAddress, sizeof(info->ifAddr) - 1);
638         info->ifAddr[sizeof(info->ifAddr) - 1] = '\0';
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, sizeof(info->subNetMask) - 1);
729             info->subNetMask[sizeof(info->subNetMask) -1] = '\0';
730             OICFree(netMask);
731         }
732
733         strncpy(info->ipAddress, multicastAddress, sizeof(info->ipAddress) - 1);
734         info->ipAddress[sizeof(info->ipAddress) -1] = '\0';
735         info->port = multicastPort;
736         info->socketFd = mulicastServerFd;
737         info->isSecured = false;
738         info->isServerStarted = true;
739         info->isMulticastServer = true;
740         strncpy(info->ifAddr, localAddress, sizeof(info->ifAddr)-1);
741         info->ifAddr[sizeof(info->ifAddr) -1] = '\0';
742
743         ret = CAAddServerInfo(g_serverInfoList, info);
744
745         if (CA_STATUS_OK != ret)
746         {
747             OIC_LOG(ERROR, IP_SERVER_TAG, "CAAddServerInfo failed!");
748             close(mulicastServerFd);
749             ca_mutex_unlock(g_mutexServerInfoList);
750             return ret;
751         }
752         ca_mutex_unlock(g_mutexServerInfoList);
753
754         ret = CAIPStartPacketReceiverHandler();
755         if (CA_STATUS_OK != ret)
756         {
757             OIC_LOG(ERROR, IP_SERVER_TAG, "CAIPStartPacketReceiverHandler failed!");
758             close(mulicastServerFd);
759             return ret;
760         }
761     }
762     else
763     {
764         OIC_LOG_V(DEBUG, IP_SERVER_TAG,
765                   "Multicast Server is already started on interface addr[%s]", localAddress);
766         ca_mutex_unlock(g_mutexServerInfoList);
767     }
768
769     OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
770     return CA_STATUS_OK;
771 }
772
773 CAResult_t CAIPStopServer(const char *interfaceAddress)
774 {
775     OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
776
777     VERIFY_NON_NULL(interfaceAddress, IP_SERVER_TAG, "interfaceAddress is NULL");
778
779     ca_mutex_lock(g_mutexServerInfoList);
780     uint32_t listIndex = 0;
781     uint32_t listLength = u_arraylist_length(g_serverInfoList);
782
783     for (listIndex = 0; listIndex < listLength;)
784     {
785         CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(g_serverInfoList, listIndex);
786         if (!info)
787         {
788             listIndex++;
789             continue;
790         }
791
792         if (info->isMulticastServer && strncmp(interfaceAddress, info->ifAddr, strlen(info->ifAddr))
793                 == 0)
794         {
795             if (u_arraylist_remove(g_serverInfoList, listIndex))
796             {
797                 struct ip_mreq multicastMemberReq = { { 0 }, { 0 } };
798
799                 multicastMemberReq.imr_interface.s_addr = inet_addr(info->ifAddr);
800                 inet_aton(info->ipAddress, &multicastMemberReq.imr_multiaddr);
801                 if (-1 == setsockopt(info->socketFd, IPPROTO_IP, IP_DROP_MEMBERSHIP,
802                                      (char *) &multicastMemberReq, sizeof(struct ip_mreq)))
803                 {
804                     OIC_LOG_V(ERROR, IP_SERVER_TAG,
805                               "Failed to leave multicast group, Error code: %s", strerror(errno));
806                 }
807                 CACloseSocket(info->socketFd);
808                 OICFree(info);
809                 OIC_LOG(DEBUG, IP_SERVER_TAG, "Multicast server is stopped successfully.");
810                 // Reduce list length by 1 as we removed one element.
811                 listLength--;
812             }
813             else
814             {
815                 OIC_LOG(ERROR, IP_SERVER_TAG, "u_arraylist_remove failed.");
816                 ca_mutex_unlock(g_mutexServerInfoList);
817                 return CA_STATUS_FAILED;
818             }
819         }
820         else if (strncmp(interfaceAddress, info->ipAddress, strlen(info->ipAddress)) == 0)
821         {
822             if (u_arraylist_remove(g_serverInfoList, listIndex))
823             {
824                 CACloseSocket(info->socketFd);
825                 OICFree(info);
826                 OIC_LOG(DEBUG, IP_SERVER_TAG, "Unicast server is stopped successfully.");
827                 // Reduce list length by 1 as we removed one element.
828                 listLength--;
829             }
830             else
831             {
832                 OIC_LOG(ERROR, IP_SERVER_TAG, "u_arraylist_remove failed.");
833                 ca_mutex_unlock(g_mutexServerInfoList);
834                 return CA_STATUS_FAILED;
835             }
836         }
837         else
838         {
839             listIndex++;
840         }
841     }
842
843     OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
844     ca_mutex_unlock(g_mutexServerInfoList);
845     return CA_STATUS_OK;
846 }
847
848 CAResult_t CAIPStopAllServers()
849 {
850     OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
851
852     g_packetHandlerStopFlag = true;
853
854     ca_mutex_lock(g_mutexServerInfoList);
855
856     uint32_t listIndex = 0;
857     uint32_t listLength = u_arraylist_length(g_serverInfoList);
858     for (listIndex = 0; listIndex < listLength;)
859     {
860         CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(g_serverInfoList, listIndex);
861         if (!info)
862         {
863             listIndex++;
864             continue;
865         }
866         if (u_arraylist_remove(g_serverInfoList, listIndex))
867         {
868             if (info->isMulticastServer)
869             {
870                 struct ip_mreq multicastMemberReq = { { 0 }, { 0 } };
871
872                 multicastMemberReq.imr_interface.s_addr = inet_addr(info->ifAddr);
873                 inet_aton(info->ipAddress, &multicastMemberReq.imr_multiaddr);
874                 if (-1 == setsockopt(info->socketFd, IPPROTO_IP, IP_DROP_MEMBERSHIP,
875                                      (char *) &multicastMemberReq, sizeof(struct ip_mreq)))
876                 {
877                     OIC_LOG_V(ERROR, IP_SERVER_TAG,
878                               "Failed to leave multicast group, Error code: %s", strerror(errno));
879                 }
880             }
881             CACloseSocket(info->socketFd);
882             //Freeing server info.
883             OICFree(info);
884             // Reduce list length by 1 as we removed one element.
885             listLength--;
886         }
887         else
888         {
889             OIC_LOG(ERROR, IP_SERVER_TAG, "u_arraylist_remove failed.");
890             ca_mutex_unlock(g_mutexServerInfoList);
891             return CA_STATUS_FAILED;
892         }
893     }
894
895     ca_mutex_unlock(g_mutexServerInfoList);
896
897     OIC_LOG(DEBUG, IP_SERVER_TAG, "All Server stopped successfully. OUT");
898     return CA_STATUS_OK;
899 }
900
901 uint16_t CAGetServerPortNum(const char *ipAddress, bool isSecured)
902 {
903     ca_mutex_lock(g_mutexServerInfoList);
904
905     uint16_t port = CAGetServerPort(g_serverInfoList, ipAddress, isSecured);
906
907     ca_mutex_unlock(g_mutexServerInfoList);
908
909     return port;
910 }
911
912 CAResult_t CAGetIPServerInfoList(u_arraylist_t **serverInfoList)
913 {
914     OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
915     ca_mutex_lock(g_mutexServerInfoList);
916
917     uint32_t list_index = 0;
918     uint32_t list_length = u_arraylist_length(g_serverInfoList);
919     for (list_index = 0; list_index < list_length; list_index++)
920     {
921         CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(g_serverInfoList, list_index);
922         if (!info)
923         {
924             continue;
925         }
926
927         CAServerInfo_t *newNetinfo = (CAServerInfo_t *) OICMalloc(sizeof(CAServerInfo_t));
928         if (!newNetinfo)
929         {
930             OIC_LOG(ERROR, IP_SERVER_TAG, "Malloc failed!");
931             ca_mutex_unlock(g_mutexServerInfoList);
932             return CA_MEMORY_ALLOC_FAILED;
933         }
934
935         memcpy(newNetinfo, info, sizeof(*info));
936
937         CAResult_t result = u_arraylist_add(*serverInfoList, (void *) newNetinfo);
938         if (CA_STATUS_OK != result)
939         {
940             OIC_LOG(ERROR, IP_SERVER_TAG, "u_arraylist_add failed!");
941             ca_mutex_unlock(g_mutexServerInfoList);
942             return CA_STATUS_FAILED;
943         }
944     }
945     ca_mutex_unlock(g_mutexServerInfoList);
946     OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
947     return CA_STATUS_OK;
948 }
949
950 void CAIPSetPacketReceiveCallback(CAIPPacketReceivedCallback callback)
951 {
952     OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
953
954     ca_mutex_lock(g_mutexAdapterServerContext);
955
956     if (!g_adapterEthServerContext)
957     {
958         OIC_LOG(ERROR, IP_SERVER_TAG, "g_adapterEthServerContext NULL");
959         ca_mutex_unlock(g_mutexAdapterServerContext);
960         return;
961     }
962     g_adapterEthServerContext->packetReceivedCallback = callback;
963
964     ca_mutex_unlock(g_mutexAdapterServerContext);
965
966     OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
967 }
968
969 void CAIPSetExceptionCallback(CAIPExceptionCallback callback)
970 {
971     OIC_LOG(DEBUG, IP_SERVER_TAG, "IN");
972     ca_mutex_lock(g_mutexAdapterServerContext);
973
974     if (!g_adapterEthServerContext)
975     {
976         OIC_LOG(ERROR, IP_SERVER_TAG, "g_adapterEthServerContext NULL");
977         ca_mutex_unlock(g_mutexAdapterServerContext);
978         return;
979     }
980     g_adapterEthServerContext->exceptionCallback = callback;
981
982     ca_mutex_unlock(g_mutexAdapterServerContext);
983
984     OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT");
985 }
986