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