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