[CONPRO-1300] Crash in CAdeinitSslAdapter
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / bt_le_adapter / caleadapter.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 #include "caleadapter.h"
21
22 #include <stdio.h>
23 #include <stdlib.h>
24
25 #include "cafragmentation.h"
26
27 #include "caleinterface.h"
28 #include "cacommon.h"
29 #include "octhread.h"
30 #include "caadapterutils.h"
31 #ifdef __WITH_DTLS__
32 #include "ca_adapter_net_ssl.h"
33 #endif
34 #ifndef SINGLE_THREAD
35 #include "caqueueingthread.h"
36 #endif
37 #if defined(__TIZEN__) || defined(__ANDROID__)
38 #include "caleserver.h"
39 #include "caleclient.h"
40 #endif
41 #include "oic_malloc.h"
42 #include "oic_string.h"
43 #include "caremotehandler.h"
44 #include <coap/pdu.h>
45
46 /**
47  * Logging tag for module name.
48  */
49 #define CALEADAPTER_TAG "OIC_CA_LE_ADAP"
50
51 /**
52  * Stores information of all the senders.
53  *
54  * This structure will be used to track and defragment all incoming data packet.
55  */
56 typedef struct
57 {
58     uint32_t recvDataLen;
59     uint32_t totalDataLen;
60     uint8_t *defragData;
61     CAEndpoint_t *remoteEndpoint;
62  } CABLESenderInfo_t;
63
64 typedef enum
65 {
66     ADAPTER_EMPTY = 1,
67     ADAPTER_BOTH_CLIENT_SERVER,
68     ADAPTER_CLIENT,
69     ADAPTER_SERVER
70 } CABLEAdapter_t;
71
72 /**
73  * mtu size to use in fragmentation logic.
74  * default value is 20 byte.
75  */
76 static uint16_t g_mtuSize = CA_DEFAULT_BLE_MTU_SIZE;
77 /**
78  * Callback to provide the status of the network change to CA layer.
79  */
80 static CAAdapterChangeCallback g_networkCallback = NULL;
81
82 /**
83  * Callback to provide the status of the connection change to CA layer.
84  */
85 static CAConnectionChangeCallback g_connectionCallback = NULL;
86
87 /**
88  * Own port value to identify packet owner. Default port value is 1.
89  */
90 static uint8_t g_localBLESourcePort = 1;
91
92 /**
93  * bleAddress of the local adapter. Value will be initialized to zero,
94  * and will be updated later.
95  */
96 static char g_localBLEAddress[18] = { 0 };
97
98 /**
99  * Variable to differentiate btw GattServer and GattClient.
100  */
101 static CABLEAdapter_t g_adapterType = ADAPTER_EMPTY;
102
103 #ifdef __WITH_DTLS__
104 static CADataType_t g_dataType = CA_REQUEST_DATA;
105 #endif
106
107 /**
108  * Mutex to synchronize the task to be executed on the GattServer
109  * function calls.
110  */
111 static oc_mutex g_bleIsServerMutex = NULL;
112
113 /**
114  * Mutex to synchronize the callback to be called for the network
115  * changes.
116  */
117 static oc_mutex g_bleNetworkCbMutex = NULL;
118
119 /**
120  * Mutex to synchronize the updates of the local LE address of the
121  * adapter.
122  */
123 static oc_mutex g_bleLocalAddressMutex = NULL;
124
125 /**
126  * Reference to thread pool.
127  */
128 static ca_thread_pool_t g_bleAdapterThreadPool = NULL;
129
130 /**
131  * Mutex to synchronize the task to be pushed to thread pool.
132  */
133 static oc_mutex g_bleAdapterThreadPoolMutex = NULL;
134
135 /**
136  * Mutex to synchronize the queing of the data from SenderQueue.
137  */
138 static oc_mutex g_bleClientSendDataMutex = NULL;
139
140 /**
141  * Mutex to synchronize the queing of the data from ReceiverQueue.
142  */
143 static oc_mutex g_bleClientReceiveDataMutex = NULL;
144
145 /**
146  * Mutex to synchronize the queing of the data from SenderQueue.
147  */
148 static oc_mutex g_bleServerSendDataMutex = NULL;
149
150 /**
151  * Mutex to synchronize the queing of the data from ReceiverQueue.
152  */
153 static oc_mutex g_bleServerReceiveDataMutex = NULL;
154
155 /**
156  * Mutex to synchronize the callback to be called for the
157  * adapterReqResponse.
158  */
159 static oc_mutex g_bleAdapterReqRespCbMutex = NULL;
160
161 /**
162  * Callback to be called when network packet received from either
163  * GattServer or GattClient.
164  */
165 static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
166
167 /**
168  * Callback to notify error from the BLE adapter.
169  */
170 static CAErrorHandleCallback g_errorHandler = NULL;
171
172 #ifdef __WITH_DTLS__
173 static CAResult_t CALESecureReceiveDataCB(const CASecureEndpoint_t *endpoint,
174                                  const void *data, size_t dataLength);
175
176 static ssize_t CALESecureSendDataCB(CAEndpoint_t *endpoint,
177                              const void *data, size_t dataLength);
178 #endif
179
180 #ifdef SINGLE_THREAD
181 /**
182  * Pointer to defragment received data from single threaded routine.
183  */
184 static CABLESenderInfo_t *g_singleThreadReceiveData = NULL;
185
186 /**
187  * This function will be associated with the receive for single thread.
188  *
189  * This function will defragment the received data from sender
190  * respectively and will send it up to CA layer. Respective sender's
191  * header will provide the length of the data sent.
192  *
193  * @param[in] data       Actual data received from the remote
194  *                       device.
195  * @param[in] dataLen    Length of the data received from the
196  *                       remote device.
197  */
198 static void CALEDataReceiverHandlerSingleThread(const uint8_t *data,
199                                                 uint32_t dataLen);
200
201 /**
202  * This function will be associated with the send for single threaded
203  * GattServer.
204  *
205  * This function will fragment the data to the MTU of the transport
206  * and send the data in fragments to the adapters. The function will
207  * be blocked until all data is sent out from the adapter.
208  *
209  * @param[in] data       Data to be transmitted from LE.
210  * @param[in] dataLen    Length of the Data being transmitted.
211  */
212 static CAResult_t CALEServerSendDataSingleThread(const uint8_t *data,
213                                                  uint32_t dataLen);
214 #endif
215
216 /**
217  * Register network change notification callback.
218  *
219  * @param[in]  netCallback  CAAdapterChangeCallback callback which will
220  *                          be set for the change in adapter.
221  * @param[in]  connCallback CAConnectionChangeCallback callback which will
222  *                          be set for the change in connection.
223  *
224  * @return  0 on success otherwise a positive error value.
225  * @retval  ::CA_STATUS_OK  Successful.
226  * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
227  * @retval  ::CA_STATUS_FAILED Operation failed.
228  *
229  */
230 static CAResult_t CALERegisterNetworkNotifications(CAAdapterChangeCallback netCallback,
231                                                    CAConnectionChangeCallback connCallback);
232
233 /**
234  * Set the thread pool handle which is required for spawning new
235  * thread.
236  *
237  * @param[in] handle Thread pool handle which is given by above layer
238  *                   for using thread creation task.
239  *
240  */
241 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle);
242
243 /**
244  * Call the callback to the upper layer when the adapter state gets
245  * changed.
246  *
247  * @param[in] adapter_state New state of the adapter to be notified to
248  *                          the upper layer.
249  */
250 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state);
251
252 /**
253  * Call the callback to the upper layer when the device connection state gets
254  * changed.
255  *
256  * @param[in] address      LE address of the device to be notified to the upper layer.
257  * @param[in] isConnected  whether connection state is connected or not.
258  */
259 static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const char* address,
260                                          bool isConnected);
261
262 /**
263  * Used to initialize all required mutex variable for LE Adapter
264  * implementation.
265  *
266  * @return  0 on success otherwise a positive error value.
267  * @retval  ::CA_STATUS_OK  Successful.
268  * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
269  * @retval  ::CA_STATUS_FAILED Operation failed.
270  *
271  */
272 static CAResult_t CAInitLEAdapterMutex();
273
274 /**
275  * Terminate all required mutex variables for LE adapter
276  * implementation.
277  */
278 static void CATerminateLEAdapterMutex();
279
280 /**
281  * Prepares and notify error through error callback.
282  */
283 static void CALEErrorHandler(const char *remoteAddress,
284                              const uint8_t *data,
285                              uint32_t dataLen,
286                              CAResult_t result);
287
288 #ifndef SINGLE_THREAD
289 /**
290  * Stop condition of Server recvhandler.
291  */
292 static bool g_dataBleServerReceiverHandlerState = false;
293
294 /**
295  * Stop condition of Client recvhandler.
296  */
297 static bool g_dataBleClientReceiverHandlerState = false;
298
299 /**
300  * Sender information of Server.
301  */
302 static u_arraylist_t *g_bleServerSenderInfo = NULL;
303
304 /**
305  * Sender information of Client.
306  */
307 static u_arraylist_t *g_bleClientSenderInfo = NULL;
308
309 /**
310  * Queue to process the outgoing packets from GATTServer.
311  */
312 static CAQueueingThread_t *g_bleServerSendQueueHandle = NULL;
313
314 /**
315  * Queue to process the outgoing packets from GATTClient.
316  */
317 static CAQueueingThread_t *g_bleClientSendQueueHandle = NULL;
318
319 /**
320  * Queue to process the incoming packets from GATTServer.
321  */
322 static CAQueueingThread_t *g_bleServerReceiverQueue = NULL;
323
324 /**
325  * Queue to process the incoming packets from GATTClient.
326  */
327 static CAQueueingThread_t *g_bleClientReceiverQueue = NULL;
328
329 /**
330  * This function will be associated with the sender queue for
331  * GattServer.
332  *
333  * This function will fragment the data to the MTU of the transport
334  * and send the data in fragments to the adapters. The function will
335  * be blocked until all data is sent out from the adapter.
336  *
337  * @param[in] threadData Data pushed to the queue which contains the
338  *                       info about RemoteEndpoint and Data.
339  */
340 static void CALEServerSendDataThread(void *threadData);
341
342 /**
343  * This function will be associated with the sender queue for
344  * GattClient.
345  *
346  * This function will fragment the data to the MTU of the transport
347  * and send the data in fragments to the adapters. The function will
348  * be blocked until all data is sent out from the adapter.
349  *
350  * @param[in] threadData Data pushed to the queue which contains the
351  *                       info about RemoteEndpoint and Data.
352  */
353 static void CALEClientSendDataThread(void *threadData);
354
355 /**
356  * This function will defragment the received data from each sender
357  * respectively and will send it up to CA layer.  Respective sender's
358  * header will provide the length of the data sent.
359  *
360  * @param[in] threadData   Data pushed to the queue which contains the
361  *                         info about RemoteEndpoint and Data.
362  * @param[in] receiverType Whether receiver is server or client.
363  */
364 static void CALEDataReceiverHandler(void *threadData, CABLEAdapter_t receiverType);
365
366 /**
367  * This function will be associated with the receiver queue for
368  * GattServer.
369  *
370  * This function will call the function CALEDataReceiverHandler()
371  * with server type to defragment the received data.
372  *
373  * @param[in] threadData Data pushed to the queue which contains the
374  *                       info about RemoteEndpoint and Data.
375  */
376 static void CALEServerDataReceiverHandler(void *threadData);
377
378 /**
379  * This function will be associated with the receiver queue for
380  * GattClient.
381  *
382  * This function will call the function CALEDataReceiverHandler()
383  * with client type to defragment the received data.
384  *
385  * @param[in] threadData Data pushed to the queue which contains the
386  *                       info about RemoteEndpoint and Data.
387  */
388 static void CALEClientDataReceiverHandler(void *threadData);
389
390 /**
391  * This function will stop all queues created for GattServer and
392  * GattClient. All four queues will be be stopped with this function
393  * invocations.
394  */
395 static void CAStopLEQueues();
396
397 /**
398  * This function will terminate all queues created for GattServer and
399  * GattClient. All four queues will be be terminated with this
400  * function invocations.
401  */
402 static void CATerminateLEQueues();
403
404 /**
405  * This function will initalize the Receiver and Sender queues for
406  * GattServer. This function will in turn call the functions
407  * CAInitBleServerReceiverQueue() and CAInitBleServerSenderQueue() to
408  * initialize the queues.
409  *
410  * @return ::CA_STATUS_OK or Appropriate error code.
411  * @retval ::CA_STATUS_OK  Successful.
412  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
413  * @retval ::CA_STATUS_FAILED Operation failed.
414  */
415 static CAResult_t CAInitLEServerQueues();
416
417 /**
418  * This function will initalize the Receiver and Sender queues for
419  * GattClient. This function will inturn call the functions
420  * CAInitBleClientReceiverQueue() and CAInitBleClientSenderQueue() to
421  * initialize the queues.
422  *
423  * @return ::CA_STATUS_OK or Appropriate error code.
424  * @retval ::CA_STATUS_OK  Successful.
425  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
426  * @retval ::CA_STATUS_FAILED Operation failed.
427  *
428  */
429 static CAResult_t CAInitLEClientQueues();
430
431 /**
432  * This function will initalize the Receiver queue for
433  * GattServer. This will initialize the queue to process the function
434  * CABLEServerSendDataThread() when ever the task is added to this
435  * queue.
436  *
437  * @return ::CA_STATUS_OK or Appropriate error code.
438  * @retval ::CA_STATUS_OK  Successful.
439  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
440  * @retval ::CA_STATUS_FAILED Operation failed.
441  */
442 static CAResult_t CAInitLEServerSenderQueue();
443
444 /**
445  * This function will initalize the Receiver queue for
446  * GattClient. This will initialize the queue to process the function
447  * CABLEClientSendDataThread() when ever the task is added to this
448  * queue.
449  *
450  * @return ::CA_STATUS_OK or Appropriate error code.
451  * @retval ::CA_STATUS_OK  Successful.
452  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
453  * @retval ::CA_STATUS_FAILED Operation failed.
454  */
455 static CAResult_t CAInitLEClientSenderQueue();
456
457 /**
458  * This function will initialize the Receiver queue for
459  * GattServer. This will initialize the queue to process the function
460  * CALEServerDataReceiverHandler() when ever the task is added to this
461  * queue.
462  *
463  * @return ::CA_STATUS_OK or Appropriate error code
464  * @retval ::CA_STATUS_OK  Successful
465  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments
466  * @retval ::CA_STATUS_FAILED Operation failed
467  *
468  */
469 static CAResult_t CAInitLEServerReceiverQueue();
470
471 /**
472  * This function will initialize the Receiver queue for
473  * GattClient. This will initialize the queue to process the function
474  * CALEClientDataReceiverHandler() when ever the task is added to this
475  * queue.
476  *
477  * @return ::CA_STATUS_OK or Appropriate error code
478  * @retval ::CA_STATUS_OK  Successful
479  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments
480  * @retval ::CA_STATUS_FAILED Operation failed
481  *
482  */
483 static CAResult_t CAInitLEClientReceiverQueue();
484
485 /**
486  * This function will create the Data required to send it in the
487  * queue.
488  *
489  * @param[in] remoteEndpoint Remote endpoint information of the
490  *                           server.
491  * @param[in] data           Data to be transmitted from LE.
492  * @param[in] dataLength     Length of the Data being transmitted.
493  *
494  * @return ::CA_STATUS_OK or Appropriate error code.
495  * @retval ::CA_STATUS_OK  Successful.
496  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
497  * @retval ::CA_STATUS_FAILED Operation failed.
498  */
499 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
500                                   const uint8_t *data,
501                                   uint32_t dataLength,
502                                   u_arraylist_t *senderInfo);
503
504 /**
505  * Used to free the BLE information stored in the sender/receiver
506  * queues.
507  *
508  * @param[in] bleData Information for a particular data segment.
509  */
510 static void CAFreeLEData(CALEData_t *bleData);
511
512 /**
513  * Free data.
514  */
515 static void CALEDataDestroyer(void *data, uint32_t size);
516
517 #ifndef SINGLE_THREAD
518 /**
519  * remove request or response data of send queue.
520  *
521  * @param[in] queueHandle    queue to process the outgoing packets.
522  * @param[in] mutex          mutex related to sender for client / server.
523  * @param[in] address        target address to remove data in queue.
524  */
525 static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle,
526                                     oc_mutex mutex,
527                                     const char* address);
528
529 /**
530  * remove all received data of data list from receive queue.
531  *
532  * @param[in] dataInfoList   received data list to remove for client / server.
533  * @param[in] address        target address to remove data in queue.
534  */
535 static void CALERemoveReceiveQueueData(u_arraylist_t *dataInfoList,
536                                        const char* address);
537
538 /**
539  * get received data info and positioned index from the received data list
540  * for client / server which is matched same leAddress and port.
541  *
542  * @param[in]  leAddress       target address to get serderInfo.
543  * @param[in]  port            target port to get serderInfo.
544  * @param[in]  senderInfoList  received data list for client / server.
545  * @param[out] senderInfo      Pointer to contain matched(leAddress and port)
546  *                             received data info.
547  * @param[out] senderIndex     Pointer to contain matched(leAddress and port)
548  *                             received data info index.
549  */
550 static CAResult_t CALEGetSenderInfo(const char *leAddress,
551                                     const uint16_t port,
552                                     u_arraylist_t *senderInfoList,
553                                     CABLESenderInfo_t **senderInfo,
554                                     uint32_t *senderIndex);
555
556 /**
557  * get ports related to remote address. It is need because multi application
558  * can have more than 2 senderInfo using same BLE address. So before remove
559  * receive queue data, should get port list from sender Info.
560  *
561  * @param[in]  leAddress       target address to get port in serderInfo.
562  * @param[in]  senderInfoList  received data list to remove for client / server.
563  * @param[out] portList        target port list related to leAddress.
564  */
565 static CAResult_t CALEGetPortsFromSenderInfo(const char *leAddress,
566                                             u_arraylist_t *senderInfoList,
567                                             u_arraylist_t *portList);
568 #endif
569
570 static CAResult_t CAInitLEServerQueues()
571 {
572     oc_mutex_lock(g_bleAdapterThreadPoolMutex);
573
574     CAResult_t result = CAInitLEServerSenderQueue();
575     if (CA_STATUS_OK != result)
576     {
577         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerSenderQueue failed");
578         oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
579         return CA_STATUS_FAILED;
580     }
581
582     g_bleServerSenderInfo = u_arraylist_create();
583     if (!g_bleServerSenderInfo)
584     {
585         OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
586         oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
587         return CA_MEMORY_ALLOC_FAILED;
588     }
589
590     result = CAInitLEServerReceiverQueue();
591     if (CA_STATUS_OK != result)
592     {
593         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerReceiverQueue failed");
594         u_arraylist_free(&g_bleServerSenderInfo);
595         oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
596         return CA_STATUS_FAILED;
597     }
598
599     g_dataBleServerReceiverHandlerState = true;
600
601     oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
602     return CA_STATUS_OK;
603 }
604
605 static CAResult_t CAInitLEClientQueues()
606 {
607     oc_mutex_lock(g_bleAdapterThreadPoolMutex);
608
609     CAResult_t result = CAInitLEClientSenderQueue();
610     if (CA_STATUS_OK != result)
611     {
612         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientSenderQueue failed");
613         oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
614         return CA_STATUS_FAILED;
615     }
616
617     g_bleClientSenderInfo = u_arraylist_create();
618     if (!g_bleClientSenderInfo)
619     {
620         OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
621         oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
622         return CA_MEMORY_ALLOC_FAILED;
623     }
624
625     result = CAInitLEClientReceiverQueue();
626     if (CA_STATUS_OK != result)
627     {
628         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientReceiverQueue failed");
629         u_arraylist_free(&g_bleClientSenderInfo);
630         oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
631         return CA_STATUS_FAILED;
632     }
633
634     g_dataBleClientReceiverHandlerState = true;
635
636     oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
637     return CA_STATUS_OK;
638 }
639
640 static CAResult_t CAInitLEServerReceiverQueue()
641 {
642     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
643     // Check if the message queue is already initialized
644     if (g_bleServerReceiverQueue)
645     {
646         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
647         return CA_STATUS_OK;
648     }
649
650     // Create recv message queue
651     g_bleServerReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
652     if (!g_bleServerReceiverQueue)
653     {
654         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
655         return CA_MEMORY_ALLOC_FAILED;
656     }
657
658     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerReceiverQueue,
659                                                    g_bleAdapterThreadPool,
660                                                    CALEServerDataReceiverHandler,
661                                                    CALEDataDestroyer))
662     {
663         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize server receiver queue thread");
664         OICFree(g_bleServerReceiverQueue);
665         g_bleServerReceiverQueue = NULL;
666         return CA_STATUS_FAILED;
667     }
668
669     if (CA_STATUS_OK != CAQueueingThreadStart(g_bleServerReceiverQueue))
670     {
671         OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
672         OICFree(g_bleServerReceiverQueue);
673         g_bleServerReceiverQueue = NULL;
674         return CA_STATUS_FAILED;
675     }
676
677     return CA_STATUS_OK;
678 }
679
680 static CAResult_t CAInitLEClientReceiverQueue()
681 {
682     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
683     // Check if the message queue is already initialized
684     if (g_bleClientReceiverQueue)
685     {
686         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
687         return CA_STATUS_OK;
688     }
689
690     // Create recv message queue
691     g_bleClientReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
692     if (!g_bleClientReceiverQueue)
693     {
694         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
695         return CA_MEMORY_ALLOC_FAILED;
696     }
697
698     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientReceiverQueue,
699                                                    g_bleAdapterThreadPool,
700                                                    CALEClientDataReceiverHandler,
701                                                    CALEDataDestroyer))
702     {
703         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize client receiver queue thread");
704         OICFree(g_bleClientReceiverQueue);
705         g_bleClientReceiverQueue = NULL;
706         return CA_STATUS_FAILED;
707     }
708
709     if (CA_STATUS_OK != CAQueueingThreadStart(g_bleClientReceiverQueue))
710     {
711         OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
712         OICFree(g_bleClientReceiverQueue);
713         g_bleClientReceiverQueue = NULL;
714         return CA_STATUS_FAILED;
715     }
716
717     return CA_STATUS_OK;
718 }
719
720 static CAResult_t CAInitLEServerSenderQueue()
721 {
722     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
723     // Check if the message queue is already initialized
724     if (g_bleServerSendQueueHandle)
725     {
726         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Queue is already initialized!");
727         return CA_STATUS_OK;
728     }
729
730     // Create send message queue
731     g_bleServerSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
732     if (!g_bleServerSendQueueHandle)
733     {
734         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
735         return CA_MEMORY_ALLOC_FAILED;
736     }
737
738     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerSendQueueHandle,
739                                                    g_bleAdapterThreadPool,
740                                                    CALEServerSendDataThread,
741                                                    CALEDataDestroyer))
742     {
743         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
744         OICFree(g_bleServerSendQueueHandle);
745         g_bleServerSendQueueHandle = NULL;
746         return CA_STATUS_FAILED;
747     }
748
749     return CA_STATUS_OK;
750 }
751
752 static void CALEClearSenderInfoImpl(u_arraylist_t ** list)
753 {
754     const size_t length = u_arraylist_length(*list);
755     for (size_t i = 0; i < length; ++i)
756     {
757         CABLESenderInfo_t * const info =
758                 (CABLESenderInfo_t *) u_arraylist_get(*list, i);
759         if (info)
760          {
761              OICFree(info->defragData);
762              CAFreeEndpoint(info->remoteEndpoint);
763              OICFree(info);
764          }
765     }
766     u_arraylist_free(list);
767 }
768
769 static void CALEClearSenderInfo()
770 {
771     CALEClearSenderInfoImpl(&g_bleServerSenderInfo);
772     CALEClearSenderInfoImpl(&g_bleClientSenderInfo);
773 }
774
775 static CAResult_t CAInitLEClientSenderQueue()
776 {
777     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
778
779     if (g_bleClientSendQueueHandle)
780     {
781         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
782         return CA_STATUS_OK;
783     }
784
785     // Create send message queue
786     g_bleClientSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
787     if (!g_bleClientSendQueueHandle)
788     {
789         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
790         return CA_MEMORY_ALLOC_FAILED;
791     }
792
793     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientSendQueueHandle,
794                                                    g_bleAdapterThreadPool,
795                                                    CALEClientSendDataThread, CALEDataDestroyer))
796     {
797         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
798         OICFree(g_bleClientSendQueueHandle);
799         g_bleClientSendQueueHandle = NULL;
800         return CA_STATUS_FAILED;
801     }
802     return CA_STATUS_OK;
803 }
804
805 static void CAStopLEQueues()
806 {
807     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
808
809     oc_mutex_lock(g_bleServerReceiveDataMutex);
810     if (NULL != g_bleServerReceiverQueue)
811     {
812         CAQueueingThreadStop(g_bleServerReceiverQueue);
813     }
814     oc_mutex_unlock(g_bleServerReceiveDataMutex);
815
816     oc_mutex_lock(g_bleClientReceiveDataMutex);
817     if (NULL != g_bleClientReceiverQueue)
818     {
819         CAQueueingThreadStop(g_bleClientReceiverQueue);
820     }
821     oc_mutex_unlock(g_bleClientReceiveDataMutex);
822
823     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
824 }
825
826 static void CATerminateLEQueues()
827 {
828     CAQueueingThreadDestroy(g_bleClientSendQueueHandle);
829     OICFree(g_bleClientSendQueueHandle);
830     g_bleClientSendQueueHandle = NULL;
831
832     CAQueueingThreadDestroy(g_bleServerSendQueueHandle);
833     OICFree(g_bleServerSendQueueHandle);
834     g_bleServerSendQueueHandle = NULL;
835
836     CAQueueingThreadDestroy(g_bleServerReceiverQueue);
837     OICFree(g_bleServerReceiverQueue);
838     g_bleServerReceiverQueue = NULL;
839
840     CAQueueingThreadDestroy(g_bleClientReceiverQueue);
841     OICFree(g_bleClientReceiverQueue);
842     g_bleClientReceiverQueue = NULL;
843
844     CALEClearSenderInfo();
845 }
846
847 static CAResult_t CALEGetSenderInfo(const char *leAddress,
848                                     const uint16_t port,
849                                     u_arraylist_t *senderInfoList,
850                                     CABLESenderInfo_t **senderInfo,
851                                     uint32_t *senderIndex)
852 {
853     VERIFY_NON_NULL_RET(leAddress,
854                         CALEADAPTER_TAG,
855                         "NULL BLE address argument",
856                         CA_STATUS_INVALID_PARAM);
857     VERIFY_NON_NULL_RET(senderIndex,
858                         CALEADAPTER_TAG,
859                         "NULL index argument",
860                         CA_STATUS_INVALID_PARAM);
861
862     const uint32_t listLength = u_arraylist_length(senderInfoList);
863     const uint32_t addrLength = strlen(leAddress);
864     for (uint32_t index = 0; index < listLength; index++)
865     {
866         CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(senderInfoList, index);
867         if (!info || !(info->remoteEndpoint))
868         {
869             continue;
870         }
871
872         if (!strncmp(info->remoteEndpoint->addr, leAddress, addrLength))
873         {
874             if (info->remoteEndpoint->port == port)
875             {
876                 *senderIndex = index;
877                 if (senderInfo)
878                 {
879                     *senderInfo = info;
880                 }
881                 return CA_STATUS_OK;
882             }
883         }
884     }
885
886     return CA_STATUS_FAILED;
887 }
888
889 static void CALEDataReceiverHandler(void *threadData, CABLEAdapter_t receiverType)
890 {
891     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
892
893     oc_mutex bleReceiveDataMutex = NULL;
894     bool dataBleReceiverHandlerState = false;
895
896     switch (receiverType)
897     {
898         case ADAPTER_CLIENT:
899             bleReceiveDataMutex = g_bleClientReceiveDataMutex;
900             dataBleReceiverHandlerState = g_dataBleClientReceiverHandlerState;
901             break;
902         case ADAPTER_SERVER:
903             bleReceiveDataMutex = g_bleServerReceiveDataMutex;
904             dataBleReceiverHandlerState = g_dataBleServerReceiverHandlerState;
905             break;
906         default:
907             OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Unsupported receiver type : %d", receiverType);
908             return;
909     }
910
911     oc_mutex_lock(bleReceiveDataMutex);
912
913     if (dataBleReceiverHandlerState)
914     {
915         CALEData_t *bleData = (CALEData_t *) threadData;
916         if (!bleData)
917         {
918             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bleData!");
919             oc_mutex_unlock(bleReceiveDataMutex);
920             return;
921         }
922
923         if (!(bleData->senderInfo))
924         {
925             OIC_LOG(ERROR, CALEADAPTER_TAG, "sender info is not available");
926             oc_mutex_unlock(bleReceiveDataMutex);
927             return;
928         }
929
930         if (!(bleData->remoteEndpoint))
931         {
932             OIC_LOG(ERROR, CALEADAPTER_TAG, "RemoteEndPoint NULL!!");
933             oc_mutex_unlock(bleReceiveDataMutex);
934             return;
935         }
936
937         CABLESenderInfo_t *senderInfo = NULL;
938         uint32_t senderIndex = 0;
939
940         //packet parsing
941         CABLEPacketStart_t startFlag = CA_BLE_PACKET_NOT_START;
942         CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
943         uint16_t sourcePort = 0;
944         uint16_t destPort = 0;
945
946         CAParseHeader(bleData->data, &startFlag, &sourcePort, &secureFlag, &destPort);
947         OIC_LOG_V(INFO, CALEADAPTER_TAG,
948                   "header info: startFlag[%X] sourcePort[%d] secureFlag[%X] destPort[%d]",
949                   startFlag, sourcePort, secureFlag, destPort);
950
951         if (destPort != g_localBLESourcePort && destPort != CA_BLE_MULTICAST_PORT)
952         {
953             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
954                       "this packet is not valid for this app(port mismatch[mine:%d, packet:%d])",
955                       g_localBLESourcePort, destPort);
956             oc_mutex_unlock(bleReceiveDataMutex);
957             return;
958         }
959
960         bleData->remoteEndpoint->port = sourcePort;
961
962         if (CA_STATUS_OK != CALEGetSenderInfo(bleData->remoteEndpoint->addr,
963                                               bleData->remoteEndpoint->port,
964                                               bleData->senderInfo,
965                                               &senderInfo, &senderIndex))
966         {
967             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This is a new client [%s:%X]",
968                       bleData->remoteEndpoint->addr, bleData->remoteEndpoint->port);
969         }
970         else
971         {
972             if (startFlag)
973             {
974                 OIC_LOG(ERROR, CALEADAPTER_TAG,
975                         "This packet is start packet but exist senderInfo. Remove senderInfo");
976                 u_arraylist_remove(bleData->senderInfo, senderIndex);
977                 OICFree(senderInfo->defragData);
978                 OICFree(senderInfo);
979                 senderInfo = NULL;
980                 senderIndex = 0;
981             }
982         }
983
984         if (!senderInfo)
985         {
986             uint32_t totalLength = 0;
987             if (startFlag)
988             {
989                 CAParseHeaderPayloadLength(bleData->data, CA_BLE_LENGTH_HEADER_SIZE, &totalLength);
990             }
991             else
992             {
993                 OIC_LOG(ERROR, CALEADAPTER_TAG, "This packet is wrong packet! ignore.");
994                 oc_mutex_unlock(bleReceiveDataMutex);
995                 return;
996             }
997
998             CABLESenderInfo_t *newSender = OICMalloc(sizeof(CABLESenderInfo_t));
999             if (!newSender)
1000             {
1001                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed for new sender");
1002                 oc_mutex_unlock(bleReceiveDataMutex);
1003                 return;
1004             }
1005             newSender->recvDataLen = 0;
1006             newSender->totalDataLen = 0;
1007             newSender->defragData = NULL;
1008             newSender->remoteEndpoint = NULL;
1009
1010             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
1011
1012             newSender->totalDataLen = totalLength;
1013
1014             if (!(newSender->totalDataLen))
1015             {
1016                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Total Data Length is parsed as 0!!!");
1017                 OICFree(newSender);
1018                 oc_mutex_unlock(bleReceiveDataMutex);
1019                 return;
1020             }
1021
1022             size_t dataOnlyLen =
1023                 bleData->dataLen - (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE);
1024             OIC_LOG_V(INFO, CALEADAPTER_TAG, "Total data to be accumulated [%u] bytes",
1025                       newSender->totalDataLen);
1026             OIC_LOG_V(INFO, CALEADAPTER_TAG, "data received in the first packet [%zu] bytes",
1027                       dataOnlyLen);
1028
1029             newSender->defragData = OICCalloc(newSender->totalDataLen + 1,
1030                                               sizeof(*newSender->defragData));
1031
1032             if (NULL == newSender->defragData)
1033             {
1034                 OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
1035                 OICFree(newSender);
1036                 oc_mutex_unlock(bleReceiveDataMutex);
1037                 return;
1038             }
1039             CATransportFlags_t flags = CA_DEFAULT_FLAGS;
1040 #ifdef __WITH_DTLS__
1041             if (CA_BLE_PACKET_SECURE == secureFlag)
1042             {
1043                 flags |= CA_SECURE;
1044             }
1045 #endif
1046
1047             const char *remoteAddress = bleData->remoteEndpoint->addr;
1048             newSender->remoteEndpoint = CACreateEndpointObject(flags,
1049                                                                CA_ADAPTER_GATT_BTLE,
1050                                                                remoteAddress,
1051                                                                bleData->remoteEndpoint->port);
1052
1053             if (NULL == newSender->remoteEndpoint)
1054             {
1055                 OIC_LOG(ERROR, CALEADAPTER_TAG, "remoteEndpoint is NULL!");
1056                 OICFree(newSender->defragData);
1057                 OICFree(newSender);
1058                 oc_mutex_unlock(bleReceiveDataMutex);
1059                 return;
1060             }
1061
1062             if (newSender->recvDataLen + dataOnlyLen > newSender->totalDataLen)
1063             {
1064                 OIC_LOG(ERROR, CALEADAPTER_TAG, "buffer is smaller than received data");
1065                 OICFree(newSender->defragData);
1066                 CAFreeEndpoint(newSender->remoteEndpoint);
1067                 OICFree(newSender);
1068                 oc_mutex_unlock(bleReceiveDataMutex);
1069                 return;
1070             }
1071             memcpy(newSender->defragData,
1072                    bleData->data + (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE),
1073                    dataOnlyLen);
1074             newSender->recvDataLen += dataOnlyLen;
1075
1076             u_arraylist_add(bleData->senderInfo,(void *)newSender);
1077
1078             //Getting newSender index position in bleSenderInfo array list
1079             if (CA_STATUS_OK !=
1080                     CALEGetSenderInfo(newSender->remoteEndpoint->addr,
1081                                       newSender->remoteEndpoint->port,
1082                                       bleData->senderInfo,
1083                                       NULL, &senderIndex))
1084             {
1085                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Existing sender index not found!!");
1086                 OICFree(newSender->defragData);
1087                 CAFreeEndpoint(newSender->remoteEndpoint);
1088                 OICFree(newSender);
1089                 oc_mutex_unlock(bleReceiveDataMutex);
1090                 return;
1091             }
1092             senderInfo = newSender;
1093         }
1094         else
1095         {
1096             size_t dataOnlyLen = bleData->dataLen - CA_BLE_HEADER_SIZE;
1097             if (senderInfo->recvDataLen + dataOnlyLen > senderInfo->totalDataLen)
1098             {
1099                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1100                           "Data Length exceeding error!! Receiving [%zu] total length [%u]",
1101                           senderInfo->recvDataLen + dataOnlyLen, senderInfo->totalDataLen);
1102                 u_arraylist_remove(bleData->senderInfo, senderIndex);
1103                 OICFree(senderInfo->defragData);
1104                 OICFree(senderInfo);
1105                 oc_mutex_unlock(bleReceiveDataMutex);
1106                 return;
1107             }
1108             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%zu]",
1109                       dataOnlyLen);
1110             memcpy(senderInfo->defragData + senderInfo->recvDataLen,
1111                    bleData->data + CA_BLE_HEADER_SIZE,
1112                    dataOnlyLen);
1113             senderInfo->recvDataLen += dataOnlyLen;
1114             OIC_LOG_V(INFO, CALEADAPTER_TAG, "totalDatalength  [%d] received Datalen [%d]",
1115                       senderInfo->totalDataLen, senderInfo->recvDataLen);
1116         }
1117
1118         if (senderInfo->totalDataLen == senderInfo->recvDataLen)
1119         {
1120             oc_mutex_lock(g_bleAdapterReqRespCbMutex);
1121             if (NULL == g_networkPacketReceivedCallback)
1122             {
1123                 OIC_LOG(ERROR, CALEADAPTER_TAG, "gReqRespCallback is NULL!");
1124
1125                 u_arraylist_remove(bleData->senderInfo, senderIndex);
1126                 OICFree(senderInfo->defragData);
1127                 OICFree(senderInfo);
1128                 oc_mutex_unlock(g_bleAdapterReqRespCbMutex);
1129                 oc_mutex_unlock(bleReceiveDataMutex);
1130                 return;
1131             }
1132
1133             OIC_LOG(DEBUG, CALEADAPTER_TAG, "[CALEDataReceiverHandler] Received data up !");
1134
1135             const CASecureEndpoint_t tmp =
1136                 {
1137                     .endpoint = *senderInfo->remoteEndpoint
1138                 };
1139
1140             OIC_LOG_V(INFO, CALEADAPTER_TAG, "endpoint flags : %d", tmp.endpoint.flags);
1141 #ifdef __WITH_DTLS__
1142             if (CA_SECURE & tmp.endpoint.flags)
1143             {
1144                 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Secure data received");
1145                 switch (receiverType)
1146                 {
1147                     case ADAPTER_CLIENT:
1148                         g_dataType = CA_REQUEST_DATA;
1149                         break;
1150                     case ADAPTER_SERVER:
1151                         g_dataType = CA_RESPONSE_DATA;
1152                         break;
1153                     default:
1154                         OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Unsupported rcvr type:%d",receiverType);
1155                         oc_mutex_unlock(g_bleAdapterReqRespCbMutex);
1156                         u_arraylist_remove(bleData->senderInfo, senderIndex);
1157                         senderInfo->remoteEndpoint = NULL;
1158                         senderInfo->defragData = NULL;
1159                         OICFree(senderInfo);
1160                         oc_mutex_unlock(bleReceiveDataMutex);
1161                         return;
1162                 }
1163
1164                 if (CA_STATUS_FAILED == CAdecryptSsl(&tmp,
1165                                                 senderInfo->defragData,
1166                                                 senderInfo->recvDataLen))
1167                 {
1168                     OIC_LOG(ERROR, CALEADAPTER_TAG, "CAdecryptSsl failed");
1169                 }
1170                 else
1171                 {
1172                     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAdecryptSsl successed");
1173                 }
1174                 OICFree(senderInfo->defragData);
1175             }
1176             else
1177             {
1178 #endif
1179                 OIC_LOG(INFO, CALEADAPTER_TAG, "Non-Secure data received");
1180                 g_networkPacketReceivedCallback(&tmp,
1181                                                 senderInfo->defragData,
1182                                                 senderInfo->recvDataLen);
1183 #ifdef __WITH_DTLS__
1184             }
1185 #endif
1186
1187             oc_mutex_unlock(g_bleAdapterReqRespCbMutex);
1188             u_arraylist_remove(bleData->senderInfo, senderIndex);
1189             senderInfo->remoteEndpoint = NULL;
1190             senderInfo->defragData = NULL;
1191             OICFree(senderInfo);
1192         }
1193     }
1194     oc_mutex_unlock(bleReceiveDataMutex);
1195 }
1196
1197
1198 static void CALEServerDataReceiverHandler(void *threadData)
1199 {
1200     CALEDataReceiverHandler(threadData, ADAPTER_SERVER);
1201 }
1202
1203 static void CALEClientDataReceiverHandler(void *threadData)
1204 {
1205     CALEDataReceiverHandler(threadData, ADAPTER_CLIENT);
1206 }
1207
1208 static void CALEServerSendDataThread(void *threadData)
1209 {
1210     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
1211
1212     CALEData_t * const bleData = (CALEData_t *) threadData;
1213     if (!bleData)
1214     {
1215         OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid bledata!");
1216         return;
1217     }
1218
1219     if (!bleData->remoteEndpoint)
1220     {
1221         OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid endpoint of bledata!");
1222         return;
1223     }
1224
1225 #if defined(__TIZEN__) || defined(__ANDROID__)
1226     // get MTU size
1227     g_mtuSize = CALEServerGetMtuSize(bleData->remoteEndpoint->addr);
1228 #endif
1229     OIC_LOG_V(INFO, CALEADAPTER_TAG, "MTU size [%d]", g_mtuSize);
1230
1231     uint32_t midPacketCount = 0;
1232     size_t remainingLen = 0;
1233     size_t totalLength = 0;
1234     CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1235
1236     CAResult_t result = CAGenerateVariableForFragmentation(bleData->dataLen,
1237                                                            &midPacketCount,
1238                                                            &remainingLen,
1239                                                            &totalLength,
1240                                                            g_mtuSize);
1241
1242     if (CA_STATUS_OK != result)
1243     {
1244         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1245                   "CAGenerateVariableForFragmentation failed, result [%d]", result);
1246         if (g_errorHandler)
1247         {
1248             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1249         }
1250         return;
1251     }
1252
1253     OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1254               "Packet info: data size[%d] midPacketCount[%u] remainingLen[%zu] totalLength[%zu]",
1255               bleData->dataLen, midPacketCount, remainingLen, totalLength);
1256
1257     OIC_LOG_V(DEBUG,
1258               CALEADAPTER_TAG,
1259               "Server total Data length with header is [%zu]",
1260               totalLength);
1261
1262     uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
1263     uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
1264
1265     if (NULL != bleData->remoteEndpoint) //Unicast Data
1266     {
1267         secureFlag = (bleData->remoteEndpoint->flags & CA_SECURE) ?
1268             CA_BLE_PACKET_SECURE : CA_BLE_PACKET_NON_SECURE;
1269
1270         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This Packet is secure? %d", secureFlag);
1271         result = CAGenerateHeader(dataHeader,
1272                                   CA_BLE_PACKET_START,
1273                                   g_localBLESourcePort,
1274                                   secureFlag,
1275                                   bleData->remoteEndpoint->port);
1276     }
1277     else                                //Multicast Data
1278     {
1279         result = CAGenerateHeader(dataHeader,
1280                                   CA_BLE_PACKET_START,
1281                                   g_localBLESourcePort,
1282                                   secureFlag,
1283                                   CA_BLE_MULTICAST_PORT);
1284     }
1285     OIC_LOG_V(INFO, CALEADAPTER_TAG, "header info: secureFlag[%X]", secureFlag);
1286
1287     if (CA_STATUS_OK != result)
1288     {
1289         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1290                   "CAGenerateHeader failed, result [%d]", result);
1291         if (g_errorHandler)
1292         {
1293             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1294         }
1295         return;
1296     }
1297
1298     uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
1299     result = CAGenerateHeaderPayloadLength(lengthHeader,
1300                                            CA_BLE_LENGTH_HEADER_SIZE,
1301                                            bleData->dataLen);
1302
1303     if (CA_STATUS_OK != result)
1304     {
1305         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1306                   "CAGenerateHeaderPayloadLength failed, result [%d]", result);
1307         if (g_errorHandler)
1308         {
1309             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1310         }
1311         return;
1312     }
1313
1314     uint32_t length = 0;
1315     uint32_t dataLen = 0;
1316     if (g_mtuSize > totalLength)
1317     {
1318         length = totalLength;
1319         dataLen = bleData->dataLen;
1320     }
1321     else
1322     {
1323         length = g_mtuSize;
1324         dataLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
1325     }
1326
1327     result = CAMakeFirstDataSegment(dataSegment,
1328                                     bleData->data, dataLen,
1329                                     dataHeader, lengthHeader);
1330
1331     if (CA_STATUS_OK != result)
1332     {
1333         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1334                   "Making data segment failed, result [%d]", result);
1335         if (g_errorHandler)
1336         {
1337             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1338         }
1339         return;
1340     }
1341
1342     const uint32_t iter = midPacketCount;
1343     uint32_t index = 0;
1344
1345     // Send the first segment with the header.
1346     if (NULL != bleData->remoteEndpoint) // Sending Unicast Data
1347     {
1348         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Unicast Data");
1349
1350         result = CAUpdateCharacteristicsToGattClient(
1351                     bleData->remoteEndpoint->addr, dataSegment, length);
1352
1353         if (CA_STATUS_OK != result)
1354         {
1355             OIC_LOG_V(ERROR,
1356                       CALEADAPTER_TAG,
1357                       "Update characteristics failed, result [%d]",
1358                       result);
1359             if (g_errorHandler)
1360             {
1361                 g_errorHandler(bleData->remoteEndpoint,
1362                                bleData->data,
1363                                bleData->dataLen,
1364                                result);
1365             }
1366             return;
1367         }
1368
1369         OIC_LOG_V(DEBUG,
1370                   CALEADAPTER_TAG,
1371                   "Server Sent Unicast First Data - data length [%zu]",
1372                   length);
1373
1374         result = CAGenerateHeader(dataHeader,
1375                                   CA_BLE_PACKET_NOT_START,
1376                                   g_localBLESourcePort,
1377                                   secureFlag,
1378                                   bleData->remoteEndpoint->port);
1379
1380         if (CA_STATUS_OK != result)
1381         {
1382             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1383                       "CAGenerateHeader failed, result [%d]", result);
1384             if (g_errorHandler)
1385             {
1386                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1387             }
1388             return;
1389         }
1390
1391         for (index = 0; index < iter; index++)
1392         {
1393             // Send the remaining header.
1394             result = CAMakeRemainDataSegment(dataSegment,
1395                                              g_mtuSize - CA_BLE_HEADER_SIZE,
1396                                              bleData->data,
1397                                              bleData->dataLen,
1398                                              index,
1399                                              dataHeader,
1400                                              g_mtuSize);
1401
1402             if (CA_STATUS_OK != result)
1403             {
1404                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1405                             "Making data segment failed, result [%d]", result);
1406                 if (g_errorHandler)
1407                 {
1408                     g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1409                 }
1410                 return;
1411             }
1412
1413             result =
1414                 CAUpdateCharacteristicsToGattClient(
1415                     bleData->remoteEndpoint->addr,
1416                     dataSegment,
1417                     g_mtuSize);
1418
1419             if (CA_STATUS_OK != result)
1420             {
1421                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1422                             "Update characteristics failed, result [%d]", result);
1423                 if (g_errorHandler)
1424                 {
1425                     g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1426                 }
1427                 return;
1428             }
1429             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]",
1430                                                g_mtuSize);
1431         }
1432
1433         if (remainingLen && (totalLength > g_mtuSize))
1434         {
1435             // send the last segment of the data (Ex: 22 bytes of 622
1436             // bytes of data when MTU is 200)
1437             result = CAMakeRemainDataSegment(dataSegment,
1438                                              remainingLen,
1439                                              bleData->data,
1440                                              bleData->dataLen,
1441                                              index,
1442                                              dataHeader,
1443                                              g_mtuSize);
1444
1445             if (CA_STATUS_OK != result)
1446             {
1447                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1448                             "Making data segment failed, result [%d]", result);
1449                 if (g_errorHandler)
1450                 {
1451                     g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1452                 }
1453                 return;
1454             }
1455
1456             result = CAUpdateCharacteristicsToGattClient(
1457                          bleData->remoteEndpoint->addr,
1458                          dataSegment,
1459                          remainingLen + CA_BLE_HEADER_SIZE);
1460
1461             if (CA_STATUS_OK != result)
1462             {
1463                 OIC_LOG_V(ERROR,
1464                           CALEADAPTER_TAG,
1465                           "Update characteristics failed, result [%d]",
1466                           result);
1467                 if (g_errorHandler)
1468                 {
1469                     g_errorHandler(bleData->remoteEndpoint,
1470                                    bleData->data,
1471                                    bleData->dataLen,
1472                                    result);
1473                 }
1474                 return;
1475             }
1476             OIC_LOG_V(DEBUG,
1477                       CALEADAPTER_TAG,
1478                       "Server Sent Unicast Last Data - data length [%zu]",
1479                       remainingLen + CA_BLE_HEADER_SIZE);
1480         }
1481      }
1482     else
1483     {
1484         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
1485         OIC_LOG(DEBUG, CALEADAPTER_TAG, "BLE Multicast is not supported");
1486     }
1487
1488     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
1489 }
1490
1491 static void CALEClientSendDataThread(void *threadData)
1492 {
1493     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
1494
1495     CALEData_t *bleData = (CALEData_t *) threadData;
1496     if (!bleData)
1497     {
1498         OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid bledata!");
1499         return;
1500     }
1501
1502     if (!bleData->remoteEndpoint)
1503     {
1504         OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid endpoint of bledata!");
1505         return;
1506     }
1507
1508 #if defined(__TIZEN__) || defined(__ANDROID__)
1509     // get MTU size
1510     if (false == CALEClientIsConnected(bleData->remoteEndpoint->addr))
1511     {
1512         // triggering to gatt connect and MTU negotiation
1513         CAResult_t res = CALEClientSendNegotiationMessage(
1514                 bleData->remoteEndpoint->addr);
1515
1516         if (CA_STATUS_OK != res)
1517         {
1518             OIC_LOG_V(ERROR,
1519                       CALEADAPTER_TAG,
1520                       "CALEClientSendNegotiationMessage has failed, result [%d]",
1521                       res);
1522             if (g_errorHandler)
1523             {
1524                 g_errorHandler(bleData->remoteEndpoint,
1525                                bleData->data,
1526                                bleData->dataLen,
1527                                res);
1528             }
1529             return;
1530         }
1531     }
1532     g_mtuSize = CALEClientGetMtuSize(bleData->remoteEndpoint->addr);
1533 #endif
1534     OIC_LOG_V(INFO, CALEADAPTER_TAG, "MTU size [%d]", g_mtuSize);
1535
1536     uint32_t midPacketCount = 0;
1537     size_t remainingLen = 0;
1538     size_t totalLength = 0;
1539     CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1540
1541     CAResult_t result = CAGenerateVariableForFragmentation(bleData->dataLen,
1542                                                            &midPacketCount,
1543                                                            &remainingLen,
1544                                                            &totalLength,
1545                                                            g_mtuSize);
1546
1547     if (CA_STATUS_OK != result)
1548     {
1549         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1550                   "CAGenerateVariableForFragmentation failed, result [%d]", result);
1551         if (g_errorHandler)
1552         {
1553             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1554         }
1555         return;
1556     }
1557
1558     OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1559               "Packet info: data size[%d] midPacketCount[%u] remainingLen[%zu] totalLength[%zu]",
1560               bleData->dataLen, midPacketCount, remainingLen, totalLength);
1561
1562     uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
1563     uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
1564
1565     if (NULL != bleData->remoteEndpoint) //Unicast Data
1566     {
1567         secureFlag = (bleData->remoteEndpoint->flags & CA_SECURE) ?
1568             CA_BLE_PACKET_SECURE : CA_BLE_PACKET_NON_SECURE;
1569
1570         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This Packet is secure? %d", secureFlag);
1571         result = CAGenerateHeader(dataHeader,
1572                                   CA_BLE_PACKET_START,
1573                                   g_localBLESourcePort,
1574                                   secureFlag,
1575                                   bleData->remoteEndpoint->port);
1576     }
1577     else                                //Multicast Data
1578     {
1579         result = CAGenerateHeader(dataHeader,
1580                                   CA_BLE_PACKET_START,
1581                                   g_localBLESourcePort,
1582                                   secureFlag,
1583                                   CA_BLE_MULTICAST_PORT);
1584     }
1585
1586     OIC_LOG_V(INFO, CALEADAPTER_TAG, "header info: secureFlag[%X]", secureFlag);
1587
1588     if (CA_STATUS_OK != result)
1589     {
1590         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1591                   "CAGenerateHeader failed, result [%d]", result);
1592         if (g_errorHandler)
1593         {
1594             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1595         }
1596         return;
1597     }
1598
1599     uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
1600     result = CAGenerateHeaderPayloadLength(lengthHeader,
1601                                            CA_BLE_LENGTH_HEADER_SIZE,
1602                                            bleData->dataLen);
1603
1604     if (CA_STATUS_OK != result)
1605     {
1606         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1607                   "CAGenerateHeaderPayloadLength failed, result [%d]", result);
1608         if (g_errorHandler)
1609         {
1610             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1611         }
1612         return;
1613     }
1614
1615     uint32_t length = 0;
1616     uint32_t dataLen = 0;
1617     if (g_mtuSize > totalLength)
1618     {
1619         length = totalLength;
1620         dataLen = bleData->dataLen;
1621     }
1622     else
1623     {
1624         length = g_mtuSize;
1625         dataLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
1626     }
1627
1628     result = CAMakeFirstDataSegment(dataSegment,
1629                                     bleData->data, dataLen,
1630                                     dataHeader, lengthHeader);
1631
1632     if (CA_STATUS_OK != result)
1633     {
1634         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1635                   "Making data segment failed, result [%d]", result);
1636         if (g_errorHandler)
1637         {
1638             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1639         }
1640         return;
1641     }
1642
1643     const uint32_t iter = midPacketCount;
1644     uint32_t index = 0;
1645     if (NULL != bleData->remoteEndpoint) //Sending Unicast Data
1646     {
1647         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Unicast Data");
1648         // Send the first segment with the header.
1649         result =
1650             CAUpdateCharacteristicsToGattServer(
1651                 bleData->remoteEndpoint->addr,
1652                 dataSegment,
1653                 length,
1654                 LE_UNICAST,
1655                 0);
1656
1657         if (CA_STATUS_OK != result)
1658         {
1659             OIC_LOG_V(ERROR,
1660                       CALEADAPTER_TAG,
1661                       "Update characteristics failed, result [%d]",
1662                       result);
1663             if (g_errorHandler)
1664             {
1665                 g_errorHandler(bleData->remoteEndpoint,
1666                                bleData->data,
1667                                bleData->dataLen,
1668                                result);
1669             }
1670             return;
1671         }
1672         OIC_LOG_V(DEBUG,
1673                   CALEADAPTER_TAG,
1674                   "Client Sent Unicast First Data - data length [%zu]",
1675                   length);
1676
1677         result = CAGenerateHeader(dataHeader,
1678                                   CA_BLE_PACKET_NOT_START,
1679                                   g_localBLESourcePort,
1680                                   secureFlag,
1681                                   bleData->remoteEndpoint->port);
1682
1683         if (CA_STATUS_OK != result)
1684         {
1685             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1686                       "CAGenerateHeader failed, result [%d]", result);
1687             if (g_errorHandler)
1688             {
1689                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1690             }
1691             return;
1692         }
1693
1694         for (index = 0; index < iter; index++)
1695         {
1696             result = CAMakeRemainDataSegment(dataSegment,
1697                                              g_mtuSize - CA_BLE_HEADER_SIZE,
1698                                              bleData->data,
1699                                              bleData->dataLen,
1700                                              index,
1701                                              dataHeader,
1702                                              g_mtuSize);
1703
1704             if (CA_STATUS_OK != result)
1705             {
1706                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1707                             "Making data segment failed, result [%d]", result);
1708                 if (g_errorHandler)
1709                 {
1710                     g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1711                 }
1712                 return;
1713             }
1714
1715             // Send the remaining header.
1716             result = CAUpdateCharacteristicsToGattServer(
1717                      bleData->remoteEndpoint->addr,
1718                      dataSegment,
1719                      g_mtuSize,
1720                      LE_UNICAST, 0);
1721
1722             if (CA_STATUS_OK != result)
1723             {
1724                 OIC_LOG_V(ERROR,
1725                           CALEADAPTER_TAG,
1726                           "Update characteristics failed, result [%d]",
1727                           result);
1728                 if (g_errorHandler)
1729                 {
1730                     g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1731                 }
1732                 return;
1733             }
1734             OIC_LOG_V(DEBUG,
1735                       CALEADAPTER_TAG,
1736                       "Client Sent Unicast %d Data - data(mtu) length [%zu]",
1737                       index + 1,
1738                       g_mtuSize);
1739         }
1740
1741         if (remainingLen && (totalLength > g_mtuSize))
1742         {
1743             // send the last segment of the data (Ex: 22 bytes of 622
1744             // bytes of data when MTU is 200)
1745             result = CAMakeRemainDataSegment(dataSegment,
1746                                              remainingLen,
1747                                              bleData->data,
1748                                              bleData->dataLen,
1749                                              index,
1750                                              dataHeader,
1751                                              g_mtuSize);
1752
1753             if (CA_STATUS_OK != result)
1754             {
1755                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1756                             "Making data segment failed, result [%d]", result);
1757                 if (g_errorHandler)
1758                 {
1759                     g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1760                 }
1761                 return;
1762             }
1763
1764             result = CAUpdateCharacteristicsToGattServer(
1765                      bleData->remoteEndpoint->addr,
1766                      dataSegment,
1767                      remainingLen + CA_BLE_HEADER_SIZE,
1768                      LE_UNICAST, 0);
1769
1770             if (CA_STATUS_OK != result)
1771             {
1772                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1773                                                    result);
1774                 if (g_errorHandler)
1775                 {
1776                     g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1777                 }
1778                 return;
1779             }
1780             OIC_LOG_V(DEBUG,
1781                       CALEADAPTER_TAG,
1782                       "Client Sent Unicast Last Data - data length [%zu]",
1783                       remainingLen + CA_BLE_HEADER_SIZE);
1784         }
1785     }
1786     else
1787     {
1788         //Sending Mulitcast Data
1789         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Client Sending Multicast Data");
1790         OIC_LOG(DEBUG, CALEADAPTER_TAG, "BLE Multicast is not supported");
1791     }
1792
1793     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
1794 }
1795
1796 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
1797                                   const uint8_t *data,
1798                                   uint32_t dataLength,
1799                                   u_arraylist_t *senderInfo)
1800 {
1801     CALEData_t * const bleData = OICMalloc(sizeof(CALEData_t));
1802
1803     if (!bleData)
1804     {
1805         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1806         return NULL;
1807     }
1808
1809     bleData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
1810     bleData->data = OICCalloc(dataLength + 1, 1);
1811
1812     if (NULL == bleData->data)
1813     {
1814         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1815         CAFreeLEData(bleData);
1816         return NULL;
1817     }
1818
1819     memcpy(bleData->data, data, dataLength);
1820     bleData->dataLen = dataLength;
1821     if (senderInfo)
1822     {
1823         bleData->senderInfo = senderInfo;
1824     }
1825
1826     return bleData;
1827 }
1828
1829 static void CAFreeLEData(CALEData_t *bleData)
1830 {
1831     VERIFY_NON_NULL_VOID(bleData, CALEADAPTER_TAG, "Param bleData is NULL");
1832
1833     CAFreeEndpoint(bleData->remoteEndpoint);
1834     OICFree(bleData->data);
1835     OICFree(bleData);
1836 }
1837
1838 static void CALEDataDestroyer(void *data, uint32_t size)
1839 {
1840     if ((size_t)size < sizeof(CALEData_t *))
1841     {
1842         OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1843                   "Destroy data too small %p %d", data, size);
1844     }
1845     CALEData_t *ledata = (CALEData_t *) data;
1846
1847     CAFreeLEData(ledata);
1848 }
1849 #endif
1850
1851 #ifdef SINGLE_THREAD
1852 static void CALEDataReceiverHandlerSingleThread(const uint8_t *data,
1853                                                 uint32_t dataLen)
1854 {
1855     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
1856
1857     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
1858
1859     //packet parsing
1860     CABLEPacketStart_t startFlag = CA_BLE_PACKET_NOT_START;
1861     CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1862     uint16_t sourcePort = 0;
1863     uint16_t destPort = 0;
1864
1865     CAParseHeader(data, &startFlag, &sourcePort, &secureFlag, &destPort);
1866     OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1867               "header info: startFlag[%X] sourcePort[%d] secureFlag[%X] destPort[%d]",
1868               startFlag, sourcePort, secureFlag, destPort);
1869
1870     if (destPort != g_localBLESourcePort && destPort != CA_BLE_MULTICAST_PORT)
1871     {
1872         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1873                   "this packet is not valid for this app(port mismatch[mine:%d, packet:%d])",
1874                   g_localBLESourcePort, destPort);
1875         return;
1876     }
1877
1878     if (startFlag)
1879     {
1880         if (g_singleThreadReceiveData)
1881         {
1882             OIC_LOG(ERROR, CALEADAPTER_TAG,
1883                     "This packet is start packet but exist senderInfo. Remove senderInfo");
1884             OICFree(g_singleThreadReceiveData->defragData);
1885             OICFree(g_singleThreadReceiveData);
1886             g_singleThreadReceiveData = NULL;
1887         }
1888
1889         uint32_t totalLength = 0;
1890         CAParseHeaderPayloadLength(data, CA_BLE_LENGTH_HEADER_SIZE, &totalLength);
1891
1892         g_singleThreadReceiveData = OICMalloc(sizeof(CABLESenderInfo_t));
1893
1894         if (!g_singleThreadReceiveData)
1895         {
1896             OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed for new sender");
1897             return;
1898         }
1899         g_singleThreadReceiveData->recvDataLen = 0;
1900         g_singleThreadReceiveData->totalDataLen = 0;
1901         g_singleThreadReceiveData->defragData = NULL;
1902         g_singleThreadReceiveData->remoteEndpoint = NULL;
1903
1904         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
1905
1906         g_singleThreadReceiveData->totalDataLen = totalLength;
1907
1908         if (!(g_singleThreadReceiveData->totalDataLen))
1909         {
1910             OIC_LOG(ERROR, CALEADAPTER_TAG, "Total Data Length is parsed as 0!!!");
1911             OICFree(g_singleThreadReceiveData);
1912             return;
1913         }
1914
1915         size_t dataOnlyLen = dataLen - (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE);
1916         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%u] bytes",
1917                   g_singleThreadReceiveData->totalDataLen);
1918         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "data received in the first packet [%u] bytes",
1919                   dataOnlyLen);
1920
1921         g_singleThreadReceiveData->defragData =
1922             OICCalloc(g_singleThreadReceiveData->totalDataLen + 1,
1923                     sizeof(*g_singleThreadReceiveData->defragData));
1924
1925         if (NULL == g_singleThreadReceiveData->defragData)
1926         {
1927             OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
1928             OICFree(g_singleThreadReceiveData);
1929             return;
1930         }
1931
1932         if (g_singleThreadReceiveData->recvDataLen + dataOnlyLen
1933                 > g_singleThreadReceiveData->totalDataLen)
1934         {
1935             OIC_LOG(ERROR, CALEADAPTER_TAG, "buffer is smaller than received data");
1936             OICFree(g_singleThreadReceiveData->defragData);
1937             OICFree(g_singleThreadReceiveData);
1938             return;
1939         }
1940         memcpy(g_singleThreadReceiveData->defragData,
1941                data + (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE),
1942                dataOnlyLen);
1943         g_singleThreadReceiveData->recvDataLen += dataOnlyLen;
1944     }
1945     else
1946     {
1947         size_t dataOnlyLen = dataLen - CA_BLE_HEADER_SIZE;
1948         if (g_singleThreadReceiveData->recvDataLen + dataOnlyLen
1949                 > g_singleThreadReceiveData->totalDataLen)
1950         {
1951             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1952                       "Data Length exceeding error!! Receiving [%d] total length [%d]",
1953                       g_singleThreadReceiveData->recvDataLen + dataOnlyLen,
1954                       g_singleThreadReceiveData->totalDataLen);
1955             OICFree(g_singleThreadReceiveData->defragData);
1956             OICFree(g_singleThreadReceiveData);
1957             return;
1958         }
1959         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%d]",
1960                   dataOnlyLen);
1961         memcpy(g_singleThreadReceiveData->defragData + g_singleThreadReceiveData->recvDataLen,
1962                data + CA_BLE_HEADER_SIZE,
1963                dataOnlyLen);
1964         g_singleThreadReceiveData->recvDataLen += dataOnlyLen;
1965         OIC_LOG_V(INFO, CALEADAPTER_TAG, "totalDatalength  [%d] received Datalen [%d]",
1966                 g_singleThreadReceiveData->totalDataLen, g_singleThreadReceiveData->recvDataLen);
1967     }
1968     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
1969 }
1970
1971 static CAResult_t CALEServerSendDataSingleThread(const uint8_t *data,
1972                                                  uint32_t dataLen)
1973 {
1974     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__););
1975
1976     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
1977
1978     uint32_t midPacketCount = 0;
1979     size_t remainingLen = 0;
1980     size_t totalLength = 0;
1981     CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1982
1983     CAResult_t result = CAGenerateVariableForFragmentation(dataLen,
1984                                                            &midPacketCount,
1985                                                            &remainingLen,
1986                                                            &totalLength,
1987                                                            g_mtuSize);
1988
1989     if (CA_STATUS_OK != result)
1990     {
1991         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1992                   "CAGenerateVariableForFragmentation failed, result [%d]", result);
1993         return result;
1994     }
1995
1996     OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1997               "Packet info: data size[%d] midPacketCount[%d] remainingLen[%d] totalLength[%d]",
1998               dataLen, midPacketCount, remainingLen, totalLength);
1999
2000     OIC_LOG_V(DEBUG,
2001               CALEADAPTER_TAG,
2002               "Server total Data length with header is [%u]",
2003               totalLength);
2004
2005     uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
2006     uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
2007
2008     result = CAGenerateHeader(dataHeader,
2009                               CA_BLE_PACKET_START,
2010                               g_localBLESourcePort,
2011                               CA_BLE_PACKET_NON_SECURE,
2012                               CA_BLE_MULTICAST_PORT);
2013
2014     if (CA_STATUS_OK != result)
2015     {
2016         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2017                   "CAGenerateHeader failed, result [%d]", result);
2018         return result;
2019     }
2020
2021     uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
2022     result = CAGenerateHeaderPayloadLength(lengthHeader,
2023                                            CA_BLE_LENGTH_HEADER_SIZE,
2024                                            dataLen);
2025
2026     if (CA_STATUS_OK != result)
2027     {
2028         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2029                   "CAGenerateHeaderPayloadLength failed, result [%d]", result);
2030         return result;
2031     }
2032
2033     uint32_t length = 0;
2034     uint32_t dataOnlyLen = 0;
2035     if (g_mtuSize > totalLength)
2036     {
2037         length = totalLength;
2038         dataOnlyLen = dataLen;
2039     }
2040     else
2041     {
2042         length = g_mtuSize;
2043         dataOnlyLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
2044     }
2045
2046     result = CAMakeFirstDataSegment(dataSegment,
2047                                     data, dataOnlyLen,
2048                                     dataHeader, lengthHeader);
2049
2050     if (CA_STATUS_OK != result)
2051     {
2052         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2053                   "Making data segment failed, result [%d]", result);
2054         return result;
2055     }
2056
2057     OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
2058     result = CAUpdateCharacteristicsToAllGattClients(dataSegment, length);
2059     if (CA_STATUS_OK != result)
2060     {
2061         OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
2062                 result);
2063         return result;
2064     }
2065
2066     CALEDoEvents();
2067
2068     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", length);
2069
2070     result = CAGenerateHeader(dataHeader,
2071                               CA_BLE_PACKET_NOT_START,
2072                               g_localBLESourcePort,
2073                               CA_BLE_PACKET_NON_SECURE,
2074                               CA_BLE_MULTICAST_PORT);
2075
2076     if (CA_STATUS_OK != result)
2077     {
2078         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2079                   "CAGenerateHeader failed, result [%d]", result);
2080         return result;
2081     }
2082
2083     const uint32_t dataLimit = midPacketCount;
2084     for (uint32_t iter = 0; iter < dataLimit; iter++)
2085     {
2086         result = CAMakeRemainDataSegment(dataSegment,
2087                                          g_mtuSize - CA_BLE_HEADER_SIZE,
2088                                          data,
2089                                          dataLen,
2090                                          iter,
2091                                          dataHeader,
2092                                          g_mtuSize);
2093
2094         if (CA_STATUS_OK != result)
2095         {
2096             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2097                     "Making data segment failed, result [%d]", result);
2098             return result;
2099         }
2100
2101         result = CAUpdateCharacteristicsToAllGattClients(
2102                      dataSegment,
2103                      g_mtuSize);
2104
2105         if (CA_STATUS_OK != result)
2106         {
2107             OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2108             return result;
2109         }
2110
2111         CALEDoEvents();
2112     }
2113
2114     if (remainingLen && (totalLength > g_mtuSize))
2115     {
2116         // send the last segment of the data
2117         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
2118
2119         result = CAMakeRemainDataSegment(dataSegment,
2120                                          remainingLen,
2121                                          data,
2122                                          dataLen,
2123                                          dataLimit,
2124                                          dataHeader,
2125                                          g_mtuSize);
2126
2127         if (CA_STATUS_OK != result)
2128         {
2129             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2130                     "Making data segment failed, result [%d]", result);
2131             return result;
2132         }
2133
2134         result = CAUpdateCharacteristicsToAllGattClients(
2135                      dataSegment,
2136                      remainingLen + CA_BLE_HEADER_SIZE);
2137
2138         if (CA_STATUS_OK != result)
2139         {
2140             OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2141             return result;
2142         }
2143         CALEDoEvents();
2144     }
2145
2146     return result;
2147 }
2148 #endif
2149
2150 static CAResult_t CAInitLEAdapterMutex()
2151 {
2152     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2153
2154     if (NULL == g_bleIsServerMutex)
2155     {
2156         g_bleIsServerMutex = oc_mutex_new();
2157         if (NULL == g_bleIsServerMutex)
2158         {
2159             OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2160             return CA_STATUS_FAILED;
2161         }
2162     }
2163
2164     if (NULL == g_bleNetworkCbMutex)
2165     {
2166         g_bleNetworkCbMutex = oc_mutex_new();
2167         if (NULL == g_bleNetworkCbMutex)
2168         {
2169             OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2170             CATerminateLEAdapterMutex();
2171             return CA_STATUS_FAILED;
2172         }
2173     }
2174
2175     if (NULL == g_bleLocalAddressMutex)
2176     {
2177         g_bleLocalAddressMutex = oc_mutex_new();
2178         if (NULL == g_bleLocalAddressMutex)
2179         {
2180             OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2181             CATerminateLEAdapterMutex();
2182             return CA_STATUS_FAILED;
2183         }
2184     }
2185
2186     if (NULL == g_bleAdapterThreadPoolMutex)
2187     {
2188         g_bleAdapterThreadPoolMutex = oc_mutex_new();
2189         if (NULL == g_bleAdapterThreadPoolMutex)
2190         {
2191             OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2192             CATerminateLEAdapterMutex();
2193             return CA_STATUS_FAILED;
2194         }
2195     }
2196
2197     if (NULL == g_bleClientSendDataMutex)
2198     {
2199         g_bleClientSendDataMutex = oc_mutex_new();
2200         if (NULL == g_bleClientSendDataMutex)
2201         {
2202             OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2203             CATerminateLEAdapterMutex();
2204             return CA_STATUS_FAILED;
2205         }
2206     }
2207
2208     if (NULL == g_bleServerSendDataMutex)
2209     {
2210         g_bleServerSendDataMutex = oc_mutex_new();
2211         if (NULL == g_bleServerSendDataMutex)
2212         {
2213             OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2214             CATerminateLEAdapterMutex();
2215             return CA_STATUS_FAILED;
2216         }
2217     }
2218
2219     if (NULL == g_bleAdapterReqRespCbMutex)
2220     {
2221         g_bleAdapterReqRespCbMutex = oc_mutex_new();
2222         if (NULL == g_bleAdapterReqRespCbMutex)
2223         {
2224             OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2225             CATerminateLEAdapterMutex();
2226             return CA_STATUS_FAILED;
2227         }
2228     }
2229
2230     if (NULL == g_bleServerReceiveDataMutex)
2231     {
2232         g_bleServerReceiveDataMutex = oc_mutex_new();
2233         if (NULL == g_bleServerReceiveDataMutex)
2234         {
2235             OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2236             return CA_STATUS_FAILED;
2237         }
2238     }
2239
2240     if (NULL == g_bleClientReceiveDataMutex)
2241     {
2242         g_bleClientReceiveDataMutex = oc_mutex_new();
2243         if (NULL == g_bleClientReceiveDataMutex)
2244         {
2245             OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2246             return CA_STATUS_FAILED;
2247         }
2248     }
2249
2250     return CA_STATUS_OK;
2251 }
2252
2253 static void CATerminateLEAdapterMutex()
2254 {
2255     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2256
2257     oc_mutex_free(g_bleIsServerMutex);
2258     g_bleIsServerMutex = NULL;
2259
2260     oc_mutex_free(g_bleNetworkCbMutex);
2261     g_bleNetworkCbMutex = NULL;
2262
2263     oc_mutex_free(g_bleLocalAddressMutex);
2264     g_bleLocalAddressMutex = NULL;
2265
2266     oc_mutex_free(g_bleAdapterThreadPoolMutex);
2267     g_bleAdapterThreadPoolMutex = NULL;
2268
2269     oc_mutex_free(g_bleClientSendDataMutex);
2270     g_bleClientSendDataMutex = NULL;
2271
2272     oc_mutex_free(g_bleServerSendDataMutex);
2273     g_bleServerSendDataMutex = NULL;
2274
2275     oc_mutex_free(g_bleAdapterReqRespCbMutex);
2276     g_bleAdapterReqRespCbMutex = NULL;
2277
2278     oc_mutex_free(g_bleServerReceiveDataMutex);
2279     g_bleServerReceiveDataMutex = NULL;
2280
2281     oc_mutex_free(g_bleClientReceiveDataMutex);
2282     g_bleClientReceiveDataMutex = NULL;
2283 }
2284
2285 /**
2286  * Starting LE connectivity adapters.
2287  *
2288  * As its peer to peer it does not require to start any servers.
2289  *
2290  * @return ::CA_STATUS_OK or Appropriate error code.
2291  */
2292 static CAResult_t CAStartLE();
2293
2294 /**
2295  * Start listening server for receiving multicast search requests.
2296  *
2297  * Transport Specific Behavior:
2298  *   LE  Starts GATT Server with prefixed UUID and Characteristics
2299  *   per OIC Specification.
2300  * @return  ::CA_STATUS_OK or Appropriate error code.
2301  */
2302 static CAResult_t CAStartLEListeningServer();
2303
2304 /**
2305  * Stops listening server from receiving multicast search requests.
2306  *
2307  * Transport Specific Behavior:
2308  *   LE  Starts GATT Server with prefixed UUID and Characteristics
2309  *   per OIC Specification.
2310  * @return  ::CA_STATUS_OK or Appropriate error code.
2311  */
2312 static CAResult_t CAStopLEListeningServer();
2313
2314 /**
2315  * Sarting discovery of servers for receiving multicast
2316  * advertisements.
2317  *
2318  * Transport Specific Behavior:
2319  *   LE  Starts GATT Server with prefixed UUID and Characteristics
2320  *   per OIC Specification.
2321  *
2322  * @return ::CA_STATUS_OK or Appropriate error code
2323  */
2324 static CAResult_t CAStartLEDiscoveryServer();
2325
2326 /**
2327  * Send data to the endpoint using the adapter connectivity.
2328  *
2329  * @param[in] endpoint Remote Endpoint information (like MAC address,
2330  *                     reference URI and connectivity type) to which
2331  *                     the unicast data has to be sent.
2332  * @param[in] data     Data which required to be sent.
2333  * @param[in] dataLen  Size of data to be sent.
2334  *
2335  * @note  dataLen must be > 0.
2336  *
2337  * @return The number of bytes sent on the network, or -1 on error.
2338  */
2339 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
2340                                    const void *data,
2341                                    uint32_t dataLen,
2342                                    CADataType_t dataType);
2343
2344 /**
2345  * Send multicast data to the endpoint using the LE connectivity.
2346  *
2347  * @param[in] endpoint Remote Endpoint information to which the
2348  *                     multicast data has to be sent.
2349  * @param[in] data     Data which required to be sent.
2350  * @param[in] dataLen  Size of data to be sent.
2351  *
2352  * @note  dataLen must be > 0.
2353  *
2354  * @return The number of bytes sent on the network, or -1 on error.
2355  */
2356 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
2357                                      const void *data,
2358                                      uint32_t dataLen,
2359                                      CADataType_t dataType);
2360
2361 /**
2362  * Get LE Connectivity network information.
2363  *
2364  * @param[out] info Local connectivity information structures.
2365  * @param[out] size Number of local connectivity structures.
2366  *
2367  * @return ::CA_STATUS_OK or Appropriate error code.
2368  */
2369 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info,
2370                                               uint32_t *size);
2371
2372 /**
2373  * Read Synchronous API callback.
2374  *
2375  * @return  ::CA_STATUS_OK or Appropriate error code.
2376  */
2377 static CAResult_t CAReadLEData();
2378
2379 /**
2380  * Stopping the adapters and close socket connections.
2381  *
2382  * LE Stops all GATT servers and GATT Clients.
2383  *
2384  * @return ::CA_STATUS_OK or Appropriate error code.
2385  */
2386 static CAResult_t CAStopLE();
2387
2388 /**
2389  * Terminate the LE connectivity adapter.
2390  *
2391  * Configuration information will be deleted from further use.
2392  */
2393 static void CATerminateLE();
2394
2395 /**
2396  * This function will receive the data from the GattServer and add the
2397  * data to the Server receiver queue.
2398  *
2399  * @param[in] remoteAddress Remote address of the device from where
2400  *                          data is received.
2401  * @param[in] data          Actual data received from the remote
2402  *                          device.
2403  * @param[in] dataLength    Length of the data received from the
2404  *                          remote device.
2405  * @param[in] sentLength    Length of the data sent from the remote
2406  *                          device.
2407  *
2408  * @return ::CA_STATUS_OK or Appropriate error code.
2409  * @retval ::CA_STATUS_OK  Successful.
2410  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
2411  * @retval ::CA_STATUS_FAILED Operation failed.
2412  *
2413  */
2414 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
2415                                                 const uint8_t *data,
2416                                                 uint32_t dataLength,
2417                                                 uint32_t *sentLength);
2418
2419 /**
2420  * This function will receive the data from the GattClient and add the
2421  * data into the Client receiver queue.
2422  *
2423  * @param[in] remoteAddress Remote address of the device from where
2424  *                          data is received.
2425  * @param[in] data          Actual data recevied from the remote
2426  *                          device.
2427  * @param[in] dataLength    Length of the data received from the
2428  *                          remote device.
2429  * @param[in] sentLength    Length of the data sent from the remote
2430  *                          device.
2431  *
2432  * @return ::CA_STATUS_OK or Appropriate error code.
2433  * @retval ::CA_STATUS_OK  Successful.
2434  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
2435  * @retval ::CA_STATUS_FAILED Operation failed.
2436  */
2437 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
2438                                                 const uint8_t *data,
2439                                                 uint32_t dataLength,
2440                                                 uint32_t *sentLength);
2441
2442 /**
2443  * Set the NetworkPacket received callback to CA layer from adapter
2444  * layer.
2445  *
2446  * @param[in] callback Callback handle sent from the upper layer.
2447  */
2448 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback);
2449
2450 /**
2451  * Push the data from CA layer to the Sender processor queue.
2452  *
2453  * @param[in] remoteEndpoint Remote endpoint information of the
2454  *                           server.
2455  * @param[in] data           Data to be transmitted from LE.
2456  * @param[in] dataLen        Length of the Data being transmitted.
2457  *
2458  * @return ::CA_STATUS_OK or Appropriate error code.
2459  * @retval ::CA_STATUS_OK  Successful.
2460  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
2461  * @retval ::CA_STATUS_FAILED Operation failed.
2462  */
2463 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
2464                                             const uint8_t *data,
2465                                             uint32_t dataLen);
2466
2467 /**
2468  * Push the data from CA layer to the Sender processor queue.
2469  *
2470  * @param[in] remoteEndpoint Remote endpoint information of the
2471  *                           server.
2472  * @param[in] data           Data to be transmitted from LE.
2473  * @param[in] dataLen        Length of the Data being transmitted.
2474  *
2475  * @return ::CA_STATUS_OK or Appropriate error code.
2476  * @retval ::CA_STATUS_OK  Successful.
2477  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
2478  * @retval ::CA_STATUS_FAILED Operation failed.
2479  */
2480 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
2481                                             const uint8_t *data,
2482                                             uint32_t dataLen);
2483
2484 static CAResult_t CALEAdapterGattServerStart()
2485 {
2486     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2487
2488     if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2489     {
2490         OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2491                   caglobals.bleFlags);
2492         return CA_STATUS_OK;
2493     }
2494
2495     CAResult_t result = CAStartLEGattServer();
2496
2497 #ifndef SINGLE_THREAD
2498     /*
2499       Don't start the server side sending queue thread until the
2500       server itself has actually started.
2501     */
2502     if (CA_STATUS_OK == result)
2503     {
2504         oc_mutex_lock(g_bleServerSendDataMutex);
2505         result = CAQueueingThreadStart(g_bleServerSendQueueHandle);
2506         oc_mutex_unlock(g_bleServerSendDataMutex);
2507
2508         if (CA_STATUS_OK != result)
2509         {
2510             OIC_LOG_V(ERROR,
2511                       CALEADAPTER_TAG,
2512                       "Unable to start server queuing thread (%d)",
2513                       result);
2514         }
2515     }
2516 #endif
2517
2518     return result;
2519 }
2520
2521 static CAResult_t CALEAdapterGattServerStop()
2522 {
2523     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2524
2525     if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2526     {
2527         OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2528                   caglobals.bleFlags);
2529         return CA_STATUS_OK;
2530     }
2531
2532 #ifndef SINGLE_THREAD
2533
2534     oc_mutex_lock(g_bleServerSendDataMutex);
2535     CAResult_t res = CAQueueingThreadStop(g_bleServerSendQueueHandle);
2536     if (CA_STATUS_OK != res)
2537     {
2538         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAQueueingThreadStop has failed");
2539     }
2540     oc_mutex_unlock(g_bleServerSendDataMutex);
2541
2542     res = CAStopLEGattServer();
2543     if (CA_STATUS_OK != res)
2544     {
2545         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAStopLEGattServer has failed");
2546     }
2547
2548     return res;
2549 #else
2550     return CAStopLEGattServer();
2551 #endif
2552 }
2553
2554 static CAResult_t CALEAdapterGattClientStart()
2555 {
2556     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2557
2558     CAResult_t result = CAStartLEGattClient();
2559
2560 #ifndef SINGLE_THREAD
2561     /*
2562       Don't start the client side sending queue thread until the
2563       client itself has actually started.
2564     */
2565     if (CA_STATUS_OK == result)
2566     {
2567         oc_mutex_lock(g_bleClientSendDataMutex);
2568         result = CAQueueingThreadStart(g_bleClientSendQueueHandle);
2569         oc_mutex_unlock(g_bleClientSendDataMutex);
2570
2571         if (CA_STATUS_OK != result)
2572         {
2573             OIC_LOG(ERROR,
2574                     CALEADAPTER_TAG,
2575                     "Unable to start client queuing thread");
2576         }
2577     }
2578 #endif
2579
2580     return result;
2581 }
2582
2583 static CAResult_t CALEAdapterGattClientStop()
2584 {
2585 #ifndef SINGLE_THREAD
2586     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2587     CAStopLEGattClient();
2588
2589     oc_mutex_lock(g_bleClientSendDataMutex);
2590     CAResult_t result = CAQueueingThreadStop(g_bleClientSendQueueHandle);
2591     oc_mutex_unlock(g_bleClientSendDataMutex);
2592
2593     return result;
2594 #else
2595     CAStopLEGattClient();
2596
2597     return CA_STATUS_OK;
2598 #endif
2599 }
2600
2601 #ifdef __WITH_DTLS__
2602 static ssize_t CALESecureSendDataCB(CAEndpoint_t *endpoint, const void *data, size_t dataLen)
2603 {
2604     VERIFY_NON_NULL(endpoint, CALEADAPTER_TAG, "endpoint is NULL");
2605     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "data is NULL");
2606     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2607     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "encrypted datalen = %d", dataLen);
2608
2609     CAResult_t result;
2610     CADataType_t dataType = g_dataType;
2611     ssize_t ret = 0;
2612
2613     if (ADAPTER_SERVER == g_adapterType ||
2614             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2615     {
2616         result = CALEAdapterServerSendData(endpoint, data, dataLen);
2617         if (CA_STATUS_OK != result)
2618         {
2619             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed" );
2620
2621              if (g_errorHandler)
2622              {
2623                  g_errorHandler(endpoint, data, dataLen, result);
2624              }
2625              return ret;
2626         }
2627         ret = (ssize_t)dataLen;
2628     }
2629     else if (ADAPTER_CLIENT == g_adapterType ||
2630             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
2631             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
2632     {
2633         result = CALEAdapterClientSendData(endpoint, data, dataLen);
2634         if (CA_STATUS_OK != result)
2635         {
2636             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for client failed" );
2637
2638              if (g_errorHandler)
2639              {
2640                  g_errorHandler(endpoint, data, dataLen, result);
2641              }
2642              return ret;
2643         }
2644         ret = (ssize_t)dataLen;
2645     }
2646     else
2647     {
2648         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2649                   "Can't Send Message adapterType = %d, dataType = %d", g_adapterType, dataType);
2650         return ret;
2651     }
2652     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2653     return ret;
2654 }
2655
2656 CAResult_t CALESecureReceiveDataCB(const CASecureEndpoint_t *sep, const void *data,
2657                           size_t dataLen)
2658 {
2659     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2660
2661     VERIFY_NON_NULL(sep, CALEADAPTER_TAG, "sep is NULL");
2662     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "data is NULL");
2663
2664     OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
2665               "Secure Data Receive - decrypted datalen = %d", dataLen);
2666
2667     if (dataLen <= 0)
2668     {
2669         OIC_LOG(ERROR, CALEADAPTER_TAG, "incorrect dataLen, derecypt fail !");
2670         return CA_STATUS_INVALID_PARAM;
2671     }
2672
2673     OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
2674
2675     CAResult_t res = CA_STATUS_OK;
2676     if (g_networkPacketReceivedCallback)
2677     {
2678         OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
2679                   "[CALESecureReceiveDataCB] Secure flags = %d, %x",
2680                   sep->endpoint.flags, sep->endpoint.flags);
2681         OIC_LOG(DEBUG, CALEADAPTER_TAG,
2682                   "[CALESecureReceiveDataCB] Received data up !");
2683         res = g_networkPacketReceivedCallback(sep, data, dataLen);
2684         if (CA_STATUS_OK != res)
2685         {
2686             OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Error parsing CoAP data, res = %d", res);
2687         }
2688     }
2689     return res;
2690 }
2691 #endif
2692
2693 CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
2694                           CANetworkPacketReceivedCallback reqRespCallback,
2695                           CAAdapterChangeCallback netCallback,
2696                           CAConnectionChangeCallback connCallback,
2697                           CAErrorHandleCallback errorCallback,
2698                           ca_thread_pool_t handle)
2699 {
2700     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2701
2702     //Input validation
2703     VERIFY_NON_NULL(registerCallback, CALEADAPTER_TAG, "RegisterConnectivity callback is null");
2704     VERIFY_NON_NULL(reqRespCallback, CALEADAPTER_TAG, "PacketReceived Callback is null");
2705     VERIFY_NON_NULL(netCallback, CALEADAPTER_TAG, "NetworkChange Callback is null");
2706     VERIFY_NON_NULL(connCallback, CALEADAPTER_TAG, "ConnectionChange Callback is null");
2707
2708     CAResult_t result = CA_STATUS_OK;
2709     result = CAInitLEAdapterMutex();
2710     if (CA_STATUS_OK != result)
2711     {
2712         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleAdapterMutex failed!");
2713         return CA_STATUS_FAILED;
2714     }
2715
2716     result = CAInitializeLENetworkMonitor();
2717     if (CA_STATUS_OK != result)
2718     {
2719         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() failed");
2720         return CA_STATUS_FAILED;
2721     }
2722     CAInitializeLEAdapter();
2723
2724     result = CAInitializeLEGattClient();
2725     if (CA_STATUS_OK != result)
2726     {
2727         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattClient() failed");
2728         return CA_STATUS_FAILED;
2729     }
2730
2731     CASetLEClientThreadPoolHandle(handle);
2732
2733     CASetLEReqRespClientCallback(CALEAdapterClientReceivedData);
2734     CASetLEServerThreadPoolHandle(handle);
2735     result = CAInitializeLEGattServer();
2736     if (CA_STATUS_OK != result)
2737     {
2738         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattServer() failed");
2739         return CA_STATUS_FAILED;
2740     }
2741
2742     CASetLEAdapterThreadPoolHandle(handle);
2743     CASetLEReqRespServerCallback(CALEAdapterServerReceivedData);
2744     CASetLEReqRespAdapterCallback(reqRespCallback);
2745
2746     CASetBLEClientErrorHandleCallback(CALEErrorHandler);
2747     CASetBLEServerErrorHandleCallback(CALEErrorHandler);
2748     CALERegisterNetworkNotifications(netCallback, connCallback);
2749
2750     g_errorHandler = errorCallback;
2751
2752 #ifdef __WITH_DTLS__
2753      if (CA_STATUS_OK != CAinitSslAdapter())
2754     {
2755         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to init SSL adapter");
2756     }
2757     else
2758     {
2759         CAsetSslAdapterCallbacks(CALESecureReceiveDataCB, CALESecureSendDataCB,
2760                                  CA_ADAPTER_GATT_BTLE);
2761     }
2762 #endif
2763
2764     static const CAConnectivityHandler_t connHandler =
2765         {
2766             .startAdapter = CAStartLE,
2767             .stopAdapter = CAStopLE,
2768             .startListenServer = CAStartLEListeningServer,
2769             .stopListenServer = CAStopLEListeningServer,
2770             .startDiscoveryServer = CAStartLEDiscoveryServer,
2771             .sendData = CASendLEUnicastData,
2772             .sendDataToAll = CASendLEMulticastData,
2773             .GetnetInfo = CAGetLEInterfaceInformation,
2774             .readData = CAReadLEData,
2775             .terminate = CATerminateLE,
2776             .cType = CA_ADAPTER_GATT_BTLE
2777         };
2778
2779     registerCallback(connHandler);
2780     return CA_STATUS_OK;
2781 }
2782
2783 static CAResult_t CAStartLE()
2784 {
2785     return CAStartLEAdapter();
2786 }
2787
2788 static CAResult_t CAStopLE()
2789 {
2790
2791 #ifndef SINGLE_THREAD
2792     CAStopLEQueues();
2793 #endif
2794
2795     oc_mutex_lock(g_bleIsServerMutex);
2796     switch (g_adapterType)
2797     {
2798         case ADAPTER_SERVER:
2799             CALEAdapterGattServerStop();
2800             break;
2801         case ADAPTER_CLIENT:
2802             CALEAdapterGattClientStop();
2803             break;
2804         case ADAPTER_BOTH_CLIENT_SERVER:
2805             CALEAdapterGattServerStop();
2806             CALEAdapterGattClientStop();
2807             break;
2808         default:
2809             break;
2810     }
2811     oc_mutex_unlock(g_bleIsServerMutex);
2812     return CAStopLEAdapter();
2813 }
2814
2815 static void CATerminateLE()
2816 {
2817     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
2818
2819     CASetLEReqRespServerCallback(NULL);
2820     CASetLEReqRespClientCallback(NULL);
2821     CALERegisterNetworkNotifications(NULL, NULL);
2822     CASetLEReqRespAdapterCallback(NULL);
2823     CATerminateLENetworkMonitor();
2824
2825     oc_mutex_lock(g_bleIsServerMutex);
2826     switch (g_adapterType)
2827     {
2828         case ADAPTER_SERVER:
2829             CATerminateLEGattServer();
2830             break;
2831         case ADAPTER_CLIENT:
2832             CATerminateLEGattClient();
2833             break;
2834         case ADAPTER_BOTH_CLIENT_SERVER:
2835             CATerminateLEGattServer();
2836             CATerminateLEGattClient();
2837             break;
2838         default:
2839             break;
2840     }
2841     g_adapterType = ADAPTER_EMPTY;
2842     oc_mutex_unlock(g_bleIsServerMutex);
2843
2844 #ifndef SINGLE_THREAD
2845     CATerminateLEQueues();
2846 #endif
2847
2848 #ifdef __WITH_DTLS__
2849     CAsetSslAdapterCallbacks(NULL, NULL, CA_ADAPTER_GATT_BTLE);
2850 #endif
2851
2852     CATerminateLEAdapterMutex();
2853 }
2854
2855 static CAResult_t CAStartLEListeningServer()
2856 {
2857     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2858
2859     if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2860     {
2861         OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2862                   caglobals.bleFlags);
2863         return CA_STATUS_OK;
2864     }
2865
2866 #ifndef ROUTING_GATEWAY
2867     CAResult_t result = CA_STATUS_OK;
2868 #ifndef SINGLE_THREAD
2869     result = CAInitLEServerQueues();
2870     if (CA_STATUS_OK != result)
2871     {
2872         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerQueues failed");
2873         return result;
2874     }
2875 #endif
2876
2877     oc_mutex_lock(g_bleIsServerMutex);
2878     switch (g_adapterType)
2879     {
2880         case ADAPTER_CLIENT:
2881             g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
2882             break;
2883         case ADAPTER_BOTH_CLIENT_SERVER:
2884             break;
2885         default:
2886             g_adapterType = ADAPTER_SERVER;
2887     }
2888     oc_mutex_unlock(g_bleIsServerMutex);
2889
2890     result = CAGetLEAdapterState();
2891     if (CA_STATUS_OK != result)
2892     {
2893         if (CA_ADAPTER_NOT_ENABLED == result)
2894         {
2895             OIC_LOG(DEBUG,
2896                     CALEADAPTER_TAG,
2897                     "Listen Server will be started once BT Adapter is enabled");
2898             result = CA_STATUS_OK;
2899         }
2900     }
2901     else
2902     {
2903         result = CALEAdapterGattServerStart();
2904     }
2905
2906     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2907     return result;
2908 #else
2909     // Routing Gateway only supports BLE client mode.
2910     OIC_LOG(ERROR, CALEADAPTER_TAG, "LE server not supported in Routing Gateway");
2911     return CA_NOT_SUPPORTED;
2912 #endif
2913 }
2914
2915 static CAResult_t CAStopLEListeningServer()
2916 {
2917     OIC_LOG(ERROR, CALEADAPTER_TAG, "Listen server stop not supported.");
2918     return CA_NOT_SUPPORTED;
2919 }
2920
2921 static CAResult_t CAStartLEDiscoveryServer()
2922 {
2923     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2924     CAResult_t result = CA_STATUS_OK;
2925 #ifndef SINGLE_THREAD
2926     result = CAInitLEClientQueues();
2927     if (CA_STATUS_OK != result)
2928     {
2929         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientQueues failed");
2930         return result;
2931     }
2932 #endif
2933
2934     oc_mutex_lock(g_bleIsServerMutex);
2935     switch (g_adapterType)
2936     {
2937         case ADAPTER_SERVER:
2938             g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
2939             break;
2940         case ADAPTER_BOTH_CLIENT_SERVER:
2941             break;
2942         default:
2943             g_adapterType = ADAPTER_CLIENT;
2944     }
2945     oc_mutex_unlock(g_bleIsServerMutex);
2946
2947     result = CAGetLEAdapterState();
2948     if (CA_STATUS_OK != result)
2949     {
2950         if (CA_ADAPTER_NOT_ENABLED == result)
2951         {
2952             OIC_LOG(DEBUG,
2953                     CALEADAPTER_TAG,
2954                     "Discovery Server will be started once BT Adapter is enabled");
2955             result = CA_STATUS_OK;
2956         }
2957     }
2958     else
2959     {
2960         result = CALEAdapterGattClientStart();
2961     }
2962
2963     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
2964     return result;
2965 }
2966
2967 static CAResult_t CAReadLEData()
2968 {
2969 #ifdef SINGLE_THREAD
2970     CACheckLEData();
2971 #endif
2972     return CA_STATUS_OK;
2973 }
2974
2975 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
2976                                    const void *data,
2977                                    uint32_t dataLen,
2978                                    CADataType_t dataType)
2979 {
2980     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
2981     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "type(%d)", dataType);
2982
2983     //Input validation
2984     VERIFY_NON_NULL_RET(endpoint, CALEADAPTER_TAG, "Remote endpoint is null", -1);
2985     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
2986
2987     CAResult_t result = CA_STATUS_FAILED;
2988
2989     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
2990     if (ADAPTER_EMPTY == g_adapterType)
2991     {
2992         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
2993     }
2994
2995     oc_mutex_lock(g_bleIsServerMutex);
2996     if (ADAPTER_SERVER == g_adapterType ||
2997             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2998     {
2999 #ifdef __WITH_DTLS__
3000         if (endpoint && endpoint->flags & CA_SECURE)
3001         {
3002             OIC_LOG(DEBUG, CALEADAPTER_TAG,
3003                     "Response Data or server - secured data send(caadapternetdtlsencrypt) call");
3004             OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
3005             g_dataType = dataType;
3006             oc_mutex_unlock(g_bleIsServerMutex);
3007
3008             result = CAencryptSsl(endpoint, (void *)data, dataLen);
3009             if (CA_STATUS_OK != result)
3010             {
3011                 OIC_LOG(ERROR, CALEADAPTER_TAG, "caadapternetdtlsencrypt failed!");
3012                 return -1;
3013             }
3014             return dataLen;
3015         }
3016         else
3017         {
3018             OIC_LOG(DEBUG, CALEADAPTER_TAG,
3019                     "server or both - none secured data send(CALEAdapterServerSendData) call");
3020             result = CALEAdapterServerSendData(endpoint, data, dataLen);
3021         }
3022 #else
3023         result = CALEAdapterServerSendData(endpoint, data, dataLen);
3024 #endif
3025         if (CA_STATUS_OK != result)
3026         {
3027             oc_mutex_unlock(g_bleIsServerMutex);
3028             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed");
3029             if (g_errorHandler)
3030             {
3031                 g_errorHandler(endpoint, data, dataLen, result);
3032             }
3033
3034             return -1;
3035         }
3036     }
3037     else if (ADAPTER_CLIENT == g_adapterType ||
3038             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
3039             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
3040     {
3041 #ifdef __WITH_DTLS__
3042         if (endpoint && endpoint->flags & CA_SECURE)
3043         {
3044             OIC_LOG(DEBUG, CALEADAPTER_TAG,
3045                     "Request Data or client - secured data send(caadapternetdtlsencrypt) call");
3046             OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
3047             g_dataType = dataType;
3048             oc_mutex_unlock(g_bleIsServerMutex);
3049
3050             result = CAencryptSsl(endpoint, (void *)data, dataLen);
3051             if (CA_STATUS_OK != result)
3052             {
3053                 OIC_LOG(ERROR, CALEADAPTER_TAG, "caadapternetdtlsencrypt failed!");
3054                 return -1;
3055             }
3056             return dataLen;
3057         }
3058         else
3059         {
3060             OIC_LOG(DEBUG, CALEADAPTER_TAG,
3061                     "client or both - none secured data send(CALEAdapterClientSendData) call");
3062             result = CALEAdapterClientSendData(endpoint, data, dataLen);
3063         }
3064 #else
3065         result = CALEAdapterClientSendData(endpoint, data, dataLen);
3066 #endif
3067         if (CA_STATUS_OK != result)
3068         {
3069             oc_mutex_unlock(g_bleIsServerMutex);
3070             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for client failed" );
3071
3072             if (g_errorHandler)
3073             {
3074                 g_errorHandler(endpoint, data, dataLen, result);
3075             }
3076             return -1;
3077         }
3078     }
3079     oc_mutex_unlock(g_bleIsServerMutex);
3080
3081     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3082     return dataLen;
3083 }
3084
3085 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
3086                                      const void *data,
3087                                      uint32_t dataLen,
3088                                      CADataType_t dataType)
3089 {
3090     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3091
3092     //Input validation
3093     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
3094
3095     if (0 >= dataLen)
3096     {
3097         OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
3098         return -1;
3099     }
3100
3101     CAResult_t result = CA_STATUS_FAILED;
3102
3103     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
3104     if (ADAPTER_EMPTY == g_adapterType)
3105     {
3106         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
3107     }
3108
3109     oc_mutex_lock(g_bleIsServerMutex);
3110     if (ADAPTER_SERVER == g_adapterType ||
3111             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
3112     {
3113         result = CALEAdapterServerSendData(NULL, data, dataLen);
3114         if (CA_STATUS_OK != result)
3115         {
3116             oc_mutex_unlock(g_bleIsServerMutex);
3117
3118             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send multicast data for server failed" );
3119
3120             if (g_errorHandler)
3121             {
3122                 g_errorHandler(endpoint, data, dataLen, result);
3123             }
3124             return -1;
3125         }
3126     }
3127
3128     if (ADAPTER_CLIENT == g_adapterType ||
3129             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
3130             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
3131     {
3132         result = CALEAdapterClientSendData(NULL, data, dataLen);
3133         if (CA_STATUS_OK != result)
3134         {
3135             oc_mutex_unlock(g_bleIsServerMutex);
3136
3137             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send Multicast data for client failed" );
3138
3139             if (g_errorHandler)
3140             {
3141                 g_errorHandler(endpoint, data, dataLen, result);
3142             }
3143             return -1;
3144         }
3145     }
3146     oc_mutex_unlock(g_bleIsServerMutex);
3147
3148     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3149     return dataLen;
3150 }
3151
3152 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
3153 {
3154     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3155
3156     VERIFY_NON_NULL(info, CALEADAPTER_TAG, "CALocalConnectivity info is null");
3157
3158     char *local_address = NULL;
3159
3160     CAResult_t res = CAGetLEAddress(&local_address);
3161     if (CA_STATUS_OK != res)
3162     {
3163         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAGetLEAddress has failed");
3164         return res;
3165     }
3166
3167     if (NULL == local_address)
3168     {
3169         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is NULL");
3170         return CA_STATUS_FAILED;
3171     }
3172
3173     *size = 0;
3174     (*info) = (CAEndpoint_t *) OICCalloc(1, sizeof(CAEndpoint_t));
3175     if (NULL == (*info))
3176     {
3177         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
3178         OICFree(local_address);
3179         return CA_STATUS_FAILED;
3180     }
3181
3182     size_t local_address_len = strlen(local_address);
3183
3184     if(local_address_len >= sizeof(g_localBLEAddress) ||
3185             local_address_len >= MAX_ADDR_STR_SIZE_CA - 1)
3186     {
3187         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is too long");
3188         OICFree(*info);
3189         OICFree(local_address);
3190         return CA_STATUS_FAILED;
3191     }
3192
3193     OICStrcpy((*info)->addr, sizeof((*info)->addr), local_address);
3194     oc_mutex_lock(g_bleLocalAddressMutex);
3195     OICStrcpy(g_localBLEAddress, sizeof(g_localBLEAddress), local_address);
3196     oc_mutex_unlock(g_bleLocalAddressMutex);
3197
3198     (*info)->adapter = CA_ADAPTER_GATT_BTLE;
3199     *size = 1;
3200     OICFree(local_address);
3201
3202     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3203     return CA_STATUS_OK;
3204 }
3205
3206 static CAResult_t CALERegisterNetworkNotifications(CAAdapterChangeCallback netCallback,
3207                                                    CAConnectionChangeCallback connCallback)
3208 {
3209     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3210
3211     oc_mutex_lock(g_bleNetworkCbMutex);
3212     g_networkCallback = netCallback;
3213     g_connectionCallback = connCallback;
3214     oc_mutex_unlock(g_bleNetworkCbMutex);
3215     CAResult_t res = CA_STATUS_OK;
3216     if (netCallback)
3217     {
3218         res = CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCb);
3219         if (CA_STATUS_OK != res)
3220         {
3221             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
3222         }
3223     }
3224     else
3225     {
3226         res = CAUnSetLEAdapterStateChangedCb();
3227         if (CA_STATUS_OK != res)
3228         {
3229             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
3230         }
3231     }
3232
3233     if (g_connectionCallback)
3234     {
3235         res = CASetLENWConnectionStateChangedCb(CALEConnectionStateChangedCb);
3236         if (CA_STATUS_OK != res)
3237         {
3238             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLENWConnectionStateChangedCb failed!");
3239         }
3240     }
3241     else
3242     {
3243         res = CAUnSetLENWConnectionStateChangedCb();
3244         if (CA_STATUS_OK != res)
3245         {
3246             OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUnSetLENWConnectionStateChangedCb failed!");
3247         }
3248     }
3249
3250     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3251     return res;
3252 }
3253
3254 static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const char* address,
3255                                          bool isConnected)
3256 {
3257     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3258
3259     VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3260     (void)adapter;
3261
3262     CAEndpoint_t localEndpoint = { .adapter = CA_ADAPTER_GATT_BTLE };
3263     OICStrcpy(localEndpoint.addr, sizeof(localEndpoint.addr), address);
3264
3265 #ifdef __TIZEN__
3266     oc_mutex_lock(g_bleIsServerMutex);
3267     switch (g_adapterType)
3268     {
3269         case ADAPTER_SERVER:
3270             CALEGattServerConnectionStateChanged(isConnected, address);
3271             break;
3272         case ADAPTER_CLIENT:
3273             CALEGattConnectionStateChanged(isConnected, address);
3274             break;
3275         case ADAPTER_BOTH_CLIENT_SERVER:
3276             CALEGattConnectionStateChanged(isConnected, address);
3277             CALEGattServerConnectionStateChanged(isConnected, address);
3278             break;
3279         default:
3280             break;
3281     }
3282     oc_mutex_unlock(g_bleIsServerMutex);
3283 #endif
3284
3285     if(!isConnected)
3286     {
3287 #ifndef SINGLE_THREAD
3288         if(g_bleClientSenderInfo)
3289         {
3290             CALERemoveReceiveQueueData(g_bleClientSenderInfo, address);
3291         }
3292
3293         if(g_bleServerSenderInfo)
3294         {
3295             CALERemoveReceiveQueueData(g_bleServerSenderInfo, address);
3296         }
3297
3298         // remove data of send queue.
3299         if (g_bleClientSendQueueHandle)
3300         {
3301             CALERemoveSendQueueData(g_bleClientSendQueueHandle,
3302                                     g_bleClientSendDataMutex,
3303                                     address);
3304         }
3305
3306         if (g_bleServerSendQueueHandle)
3307         {
3308             CALERemoveSendQueueData(g_bleServerSendQueueHandle,
3309                                     g_bleServerSendDataMutex,
3310                                     address);
3311         }
3312 #endif
3313
3314 #ifdef __WITH_DTLS__
3315         CAcloseSslConnection(&localEndpoint);
3316 #endif
3317     }
3318
3319     if (g_connectionCallback)
3320     {
3321         g_connectionCallback(&localEndpoint, isConnected);
3322     }
3323
3324     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3325 }
3326
3327 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state)
3328 {
3329     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3330
3331     if (CA_ADAPTER_ENABLED == adapter_state)
3332     {
3333         oc_mutex_lock(g_bleIsServerMutex);
3334         switch (g_adapterType)
3335         {
3336             case ADAPTER_SERVER:
3337                 CALEAdapterGattServerStart();
3338                 break;
3339             case ADAPTER_CLIENT:
3340                 CALEAdapterGattClientStart();
3341                 break;
3342             case ADAPTER_BOTH_CLIENT_SERVER:
3343                 CALEAdapterGattServerStart();
3344                 CALEAdapterGattClientStart();
3345                 break;
3346             default:
3347                 break;
3348         }
3349         oc_mutex_unlock(g_bleIsServerMutex);
3350     }
3351     else
3352     {
3353         oc_mutex_lock(g_bleIsServerMutex);
3354         switch (g_adapterType)
3355         {
3356             case ADAPTER_SERVER:
3357                 CALEAdapterGattServerStop();
3358                 break;
3359             case ADAPTER_CLIENT:
3360                 CALEAdapterGattClientStop();
3361                 break;
3362             case ADAPTER_BOTH_CLIENT_SERVER:
3363                 CALEAdapterGattServerStop();
3364                 CALEAdapterGattClientStop();
3365                 break;
3366             default:
3367                 break;
3368         }
3369         oc_mutex_unlock(g_bleIsServerMutex);
3370     }
3371
3372     if (NULL != g_networkCallback)
3373     {
3374         g_networkCallback(CA_ADAPTER_GATT_BTLE, adapter_state);
3375     }
3376     else
3377     {
3378         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_networkCallback is NULL");
3379     }
3380
3381     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3382 }
3383
3384 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
3385                                             const uint8_t *data,
3386                                             uint32_t dataLen)
3387 {
3388     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
3389 #ifndef SINGLE_THREAD
3390     VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
3391                         "g_bleClientSendQueueHandle is  NULL",
3392                         CA_STATUS_FAILED);
3393     VERIFY_NON_NULL_RET(g_bleClientSendDataMutex, CALEADAPTER_TAG,
3394                         "g_bleClientSendDataMutex is NULL",
3395                         CA_STATUS_FAILED);
3396
3397     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%u]", dataLen);
3398
3399     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen, NULL);
3400     if (!bleData)
3401     {
3402         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3403         return CA_MEMORY_ALLOC_FAILED;
3404     }
3405     // Add message to send queue
3406     oc_mutex_lock(g_bleClientSendDataMutex);
3407     CAQueueingThreadAddData(g_bleClientSendQueueHandle, bleData, sizeof(CALEData_t));
3408     oc_mutex_unlock(g_bleClientSendDataMutex);
3409 #endif
3410     return CA_STATUS_OK;
3411 }
3412
3413 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
3414                                             const uint8_t *data,
3415                                             uint32_t dataLen)
3416 {
3417     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3418
3419     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
3420
3421 #ifdef SINGLE_THREAD
3422     if (!CAIsLEConnected())
3423     {
3424         OIC_LOG(ERROR, CALEADAPTER_TAG, "le not conn");
3425         return CA_STATUS_FAILED;
3426     }
3427
3428     CAResult_t result = CALEServerSendDataSingleThread(data, dataLen);
3429     if (CA_STATUS_OK != result)
3430     {
3431         OIC_LOG(ERROR, CALEADAPTER_TAG, "CALEServerSendDataSingleThread failed");
3432         return CA_STATUS_FAILED;
3433     }
3434 #else
3435     VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG,
3436                         "BleClientReceiverQueue is NULL",
3437                         CA_STATUS_FAILED);
3438     VERIFY_NON_NULL_RET(g_bleServerSendDataMutex, CALEADAPTER_TAG,
3439                         "BleClientSendDataMutex is NULL",
3440                         CA_STATUS_FAILED);
3441
3442     VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG, "sendQueueHandle",
3443                         CA_STATUS_FAILED);
3444
3445     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
3446
3447     CALEData_t * const bleData =
3448         CACreateLEData(remoteEndpoint, data, dataLen, NULL);
3449
3450     if (!bleData)
3451     {
3452         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3453         return CA_MEMORY_ALLOC_FAILED;
3454     }
3455
3456     // Add message to send queue
3457     oc_mutex_lock(g_bleServerSendDataMutex);
3458     CAQueueingThreadAddData(g_bleServerSendQueueHandle,
3459                             bleData,
3460                             sizeof(CALEData_t));
3461     oc_mutex_unlock(g_bleServerSendDataMutex);
3462 #endif
3463     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3464     return CA_STATUS_OK;
3465 }
3466
3467 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
3468                                                 const uint8_t *data,
3469                                                 uint32_t dataLength,
3470                                                 uint32_t *sentLength)
3471 {
3472     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3473
3474     //Input validation
3475     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
3476     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
3477
3478 #ifdef SINGLE_THREAD
3479     CALEDataReceiverHandlerSingleThread(data, dataLength);
3480
3481     if (g_singleThreadReceiveData->totalDataLen == g_singleThreadReceiveData->recvDataLen)
3482     {
3483         if(g_networkPacketReceivedCallback)
3484         {
3485             // will be filled by upper layer
3486             const CASecureEndpoint_t endpoint =
3487                 { .endpoint = { .adapter = CA_ADAPTER_GATT_BTLE } };
3488
3489             g_networkPacketReceivedCallback(&endpoint,
3490                                             g_singleThreadReceiveData->defragData,
3491                                             g_singleThreadReceiveData->recvDataLen);
3492         }
3493         g_singleThreadReceiveData->remoteEndpoint = NULL;
3494         OICFree(g_singleThreadReceiveData->defragData);
3495         g_singleThreadReceiveData->defragData = NULL;
3496         OICFree(g_singleThreadReceiveData);
3497         g_singleThreadReceiveData = NULL;
3498     }
3499 #else
3500     VERIFY_NON_NULL_RET(g_bleServerReceiverQueue,
3501                         CALEADAPTER_TAG,
3502                         "g_bleServerReceiverQueue",
3503                         CA_STATUS_FAILED);
3504
3505     //Add message to data queue
3506     CAEndpoint_t * const remoteEndpoint =
3507         CACreateEndpointObject(CA_DEFAULT_FLAGS,
3508                                CA_ADAPTER_GATT_BTLE,
3509                                remoteAddress,
3510                                0);
3511
3512     if (NULL == remoteEndpoint)
3513     {
3514         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
3515         return CA_STATUS_FAILED;
3516     }
3517
3518     // Create bleData to add to queue
3519     OIC_LOG_V(DEBUG,
3520               CALEADAPTER_TAG,
3521               "Data received from LE Server layer [%d]",
3522               dataLength);
3523
3524     CALEData_t * const bleData =
3525         CACreateLEData(remoteEndpoint, data, dataLength, g_bleServerSenderInfo);
3526
3527     if (!bleData)
3528     {
3529         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3530         CAFreeEndpoint(remoteEndpoint);
3531         return CA_MEMORY_ALLOC_FAILED;
3532     }
3533
3534     CAFreeEndpoint(remoteEndpoint);
3535     // Add message to receiver queue
3536     CAQueueingThreadAddData(g_bleServerReceiverQueue, bleData, sizeof(CALEData_t));
3537
3538     *sentLength = dataLength;
3539 #endif
3540     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3541     return CA_STATUS_OK;
3542 }
3543
3544 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
3545                                                 const uint8_t *data,
3546                                                 uint32_t dataLength,
3547                                                 uint32_t *sentLength)
3548 {
3549     //Input validation
3550     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
3551     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
3552 #ifndef SINGLE_THREAD
3553     VERIFY_NON_NULL_RET(g_bleClientReceiverQueue, CALEADAPTER_TAG,
3554                         "g_bleClientReceiverQueue",
3555                         CA_STATUS_FAILED);
3556
3557     //Add message to data queue
3558     CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
3559                                                           CA_ADAPTER_GATT_BTLE,
3560                                                           remoteAddress, 0);
3561     if (NULL == remoteEndpoint)
3562     {
3563         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
3564         return CA_STATUS_FAILED;
3565     }
3566
3567     // Create bleData to add to queue
3568     OIC_LOG_V(DEBUG,
3569               CALEADAPTER_TAG,
3570               "Data received from LE Client layer [%zu]",
3571               dataLength);
3572
3573     CALEData_t * const bleData =
3574         CACreateLEData(remoteEndpoint, data, dataLength, g_bleClientSenderInfo);
3575
3576     if (!bleData)
3577     {
3578         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
3579         CAFreeEndpoint(remoteEndpoint);
3580         return CA_MEMORY_ALLOC_FAILED;
3581     }
3582
3583     CAFreeEndpoint(remoteEndpoint);
3584     // Add message to receiver queue
3585     CAQueueingThreadAddData(g_bleClientReceiverQueue, bleData, sizeof(CALEData_t));
3586
3587     *sentLength = dataLength;
3588 #endif
3589     return CA_STATUS_OK;
3590 }
3591
3592 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle)
3593 {
3594     oc_mutex_lock(g_bleAdapterThreadPoolMutex);
3595     g_bleAdapterThreadPool = handle;
3596     oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
3597 }
3598
3599 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback)
3600 {
3601     oc_mutex_lock(g_bleAdapterReqRespCbMutex);
3602
3603     g_networkPacketReceivedCallback = callback;
3604
3605     oc_mutex_unlock(g_bleAdapterReqRespCbMutex);
3606 }
3607
3608 static void CALEErrorHandler(const char *remoteAddress,
3609                              const uint8_t *data,
3610                              uint32_t dataLen,
3611                              CAResult_t result)
3612 {
3613     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3614
3615     VERIFY_NON_NULL_VOID(data, CALEADAPTER_TAG, "Data is null");
3616
3617     CAEndpoint_t *rep = CACreateEndpointObject(CA_DEFAULT_FLAGS,
3618                                                CA_ADAPTER_GATT_BTLE,
3619                                                remoteAddress,
3620                                                0);
3621
3622     // if required, will be used to build remote endpoint
3623     g_errorHandler(rep, data, dataLen, result);
3624
3625     CAFreeEndpoint(rep);
3626
3627     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3628 }
3629
3630 #ifndef SINGLE_THREAD
3631 static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle, oc_mutex mutex,
3632                                     const char* address)
3633 {
3634     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
3635
3636     VERIFY_NON_NULL_VOID(queueHandle, CALEADAPTER_TAG, "queueHandle");
3637     VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3638
3639     oc_mutex_lock(mutex);
3640     oc_mutex_lock(queueHandle->threadMutex);
3641     while (u_queue_get_size(queueHandle->dataQueue) > 0)
3642     {
3643         OIC_LOG(DEBUG, CALEADAPTER_TAG, "get data from queue");
3644         u_queue_message_t *message = u_queue_get_element(queueHandle->dataQueue);
3645         if (NULL != message)
3646         {
3647             CALEData_t *bleData = (CALEData_t *) message->msg;
3648             if (bleData && bleData->remoteEndpoint)
3649             {
3650                 if (!strcasecmp(bleData->remoteEndpoint->addr, address))
3651                 {
3652                     OIC_LOG(DEBUG, CALEADAPTER_TAG, "found the message of disconnected device");
3653                     if (NULL != queueHandle->destroy)
3654                     {
3655                         queueHandle->destroy(message->msg, message->size);
3656                     }
3657                     else
3658                     {
3659                         OICFree(message->msg);
3660                     }
3661
3662                     OICFree(message);
3663                 }
3664             }
3665         }
3666     }
3667     oc_mutex_unlock(queueHandle->threadMutex);
3668     oc_mutex_unlock(mutex);
3669 }
3670
3671 static void CALERemoveReceiveQueueData(u_arraylist_t *dataInfoList, const char* address)
3672 {
3673     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "%s", __func__);
3674
3675     VERIFY_NON_NULL_VOID(dataInfoList, CALEADAPTER_TAG, "dataInfoList");
3676     VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
3677
3678     CABLESenderInfo_t *senderInfo = NULL;
3679     uint32_t senderIndex = 0;
3680
3681     u_arraylist_t *portList = u_arraylist_create();
3682     if (CA_STATUS_OK == CALEGetPortsFromSenderInfo(address, dataInfoList, portList))
3683     {
3684         uint32_t arrayLength = u_arraylist_length(portList);
3685         for (uint32_t i = 0; i < arrayLength; i++)
3686         {
3687             uint16_t *port = (uint16_t *)u_arraylist_get(portList, i);
3688             if (!port)
3689             {
3690                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to get port from sender info !");
3691                 u_arraylist_destroy(portList);
3692                 return;
3693             }
3694
3695             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "port : %X", *port);
3696
3697             if (CA_STATUS_OK == CALEGetSenderInfo(address, *port,
3698                                                   dataInfoList, &senderInfo,
3699                                                   &senderIndex))
3700             {
3701                 u_arraylist_remove(dataInfoList, senderIndex);
3702                 OICFree(senderInfo->defragData);
3703                 OICFree(senderInfo->remoteEndpoint);
3704                 OICFree(senderInfo);
3705
3706                 OIC_LOG(DEBUG, CALEADAPTER_TAG,
3707                         "SenderInfo is removed for disconnection");
3708             }
3709             else
3710             {
3711                 OIC_LOG(DEBUG, CALEADAPTER_TAG, "SenderInfo doesn't exist");
3712             }
3713         }
3714     }
3715     u_arraylist_destroy(portList);
3716 }
3717
3718 static CAResult_t CALEGetPortsFromSenderInfo(const char *leAddress,
3719                                             u_arraylist_t *senderInfoList,
3720                                             u_arraylist_t *portList)
3721 {
3722     VERIFY_NON_NULL(leAddress,
3723                     CALEADAPTER_TAG,
3724                     "NULL BLE address argument");
3725
3726     const uint32_t listLength = u_arraylist_length(senderInfoList);
3727     const uint32_t addrLength = strlen(leAddress);
3728
3729     for (uint32_t index = 0; index < listLength; index++)
3730     {
3731         CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(senderInfoList, index);
3732         if (!info || !(info->remoteEndpoint))
3733         {
3734             continue;
3735         }
3736
3737         if (!strncmp(info->remoteEndpoint->addr, leAddress, addrLength))
3738         {
3739             uint16_t *port = (uint16_t *)OICMalloc(sizeof(uint16_t));
3740             if (!port)
3741             {
3742                 OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
3743                 return CA_MEMORY_ALLOC_FAILED;
3744             }
3745             *port = info->remoteEndpoint->port;
3746             u_arraylist_add(portList, (void *)port);
3747         }
3748     }
3749
3750     if (u_arraylist_length(portList) != 0)
3751     {
3752         return CA_STATUS_OK;
3753     }
3754     else
3755     {
3756         return CA_STATUS_FAILED;
3757     }
3758 }
3759 #endif
3760
3761 void CALEStartGattServer()
3762 {
3763     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3764
3765     oc_mutex_lock(g_bleIsServerMutex);
3766     switch (g_adapterType)
3767     {
3768         case ADAPTER_SERVER:
3769             CALEAdapterGattServerStart();
3770              break;
3771         case ADAPTER_CLIENT:
3772             CALEAdapterGattClientStart();
3773             break;
3774         case ADAPTER_BOTH_CLIENT_SERVER:
3775             CALEAdapterGattServerStart();
3776             CALEAdapterGattClientStart();
3777             break;
3778         default:
3779             break;
3780     }
3781     oc_mutex_unlock(g_bleIsServerMutex);
3782     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3783 }
3784
3785 void CALEStopGattServer()
3786 {
3787     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN %s", __func__);
3788
3789     oc_mutex_lock(g_bleIsServerMutex);
3790     switch (g_adapterType)
3791     {
3792         case ADAPTER_SERVER:
3793             CALEAdapterGattServerStop();
3794             break;
3795         case ADAPTER_CLIENT:
3796             CALEAdapterGattClientStop();
3797             break;
3798         case ADAPTER_BOTH_CLIENT_SERVER:
3799             CALEAdapterGattServerStop();
3800             CALEAdapterGattClientStop();
3801             break;
3802         default:
3803             break;
3804     }
3805     oc_mutex_unlock(g_bleIsServerMutex);
3806     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT %s", __func__);
3807 }