Drop arduino support: SINGLE_THREAD
[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 #include <inttypes.h>
25
26 #include "cafragmentation.h"
27
28 #include "caleinterface.h"
29 #include "cacommon.h"
30 #include "octhread.h"
31 #include "caadapterutils.h"
32 #ifdef __WITH_DTLS__
33 #include "ca_adapter_net_ssl.h"
34 #endif
35 #include "caqueueingthread.h"
36 #if defined(__TIZEN__) || defined(__ANDROID__)
37 #include "caleserver.h"
38 #include "caleclient.h"
39 #endif
40 #include "oic_malloc.h"
41 #include "oic_string.h"
42 #include "caremotehandler.h"
43 #include <coap/pdu.h>
44
45 /**
46  * Logging tag for module name.
47  */
48 #define CALEADAPTER_TAG "OIC_CA_LE_ADAP"
49
50 /**
51  * Stores information of all the senders.
52  *
53  * This structure will be used to track and defragment all incoming data packet.
54  */
55 typedef struct
56 {
57     uint32_t recvDataLen;
58     uint32_t totalDataLen;
59     uint8_t *defragData;
60     CAEndpoint_t *remoteEndpoint;
61  } CABLESenderInfo_t;
62
63 typedef enum
64 {
65     ADAPTER_EMPTY = 1,
66     ADAPTER_BOTH_CLIENT_SERVER,
67     ADAPTER_CLIENT,
68     ADAPTER_SERVER
69 } CABLEAdapter_t;
70
71 /**
72  * mtu size to use in fragmentation logic.
73  * default value is 20 byte.
74  */
75 static uint16_t g_mtuSize = CA_DEFAULT_BLE_MTU_SIZE;
76 /**
77  * Callback to provide the status of the network change to CA layer.
78  */
79 static CAAdapterChangeCallback g_networkCallback = NULL;
80
81 /**
82  * Callback to provide the status of the connection change to CA layer.
83  */
84 static CAConnectionChangeCallback g_connectionCallback = NULL;
85
86 /**
87  * Own port value to identify packet owner. Default port value is 1.
88  */
89 static uint8_t g_localBLESourcePort = 1;
90
91 /**
92  * bleAddress of the local adapter. Value will be initialized to zero,
93  * and will be updated later.
94  */
95 static char g_localBLEAddress[18] = { 0 };
96
97 /**
98  * Variable to differentiate btw GattServer and GattClient.
99  */
100 static CABLEAdapter_t g_adapterType = ADAPTER_EMPTY;
101
102 #ifdef __WITH_DTLS__
103 /**
104  * Variable for storing data type during dtls encryption.
105  */
106 static CADataType_t g_dataType = CA_REQUEST_DATA;
107 #endif
108
109 /**
110  * Mutex to synchronize the task to be executed on the GattServer
111  * function calls.
112  */
113 static oc_mutex g_bleIsServerMutex = NULL;
114
115 /**
116  * Mutex to synchronize the callback to be called for the network
117  * changes.
118  */
119 static oc_mutex g_bleNetworkCbMutex = NULL;
120
121 /**
122  * Mutex to synchronize the updates of the local LE address of the
123  * adapter.
124  */
125 static oc_mutex g_bleLocalAddressMutex = NULL;
126
127 /**
128  * Reference to thread pool.
129  */
130 static ca_thread_pool_t g_bleAdapterThreadPool = NULL;
131
132 /**
133  * Mutex to synchronize the task to be pushed to thread pool.
134  */
135 static oc_mutex g_bleAdapterThreadPoolMutex = NULL;
136
137 /**
138  * Mutex to synchronize the queing of the data from SenderQueue.
139  */
140 static oc_mutex g_bleClientSendDataMutex = NULL;
141
142 /**
143  * Mutex to synchronize the queing of the data from ReceiverQueue.
144  */
145 static oc_mutex g_bleClientReceiveDataMutex = NULL;
146
147 /**
148  * Mutex to synchronize the queing of the data from SenderQueue.
149  */
150 static oc_mutex g_bleServerSendDataMutex = NULL;
151
152 /**
153  * Mutex to synchronize the queing of the data from ReceiverQueue.
154  */
155 static oc_mutex g_bleServerReceiveDataMutex = NULL;
156
157 /**
158  * Mutex to synchronize the callback to be called for the
159  * adapterReqResponse.
160  */
161 static oc_mutex g_bleAdapterReqRespCbMutex = NULL;
162
163 /**
164  * Callback to be called when network packet received from either
165  * GattServer or GattClient.
166  */
167 static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
168
169 /**
170  * Callback to notify error from the BLE adapter.
171  */
172 static CAErrorHandleCallback g_errorHandler = NULL;
173
174 #ifdef __WITH_DTLS__
175 /**
176  * Callback to receive decrypted data from the ssl adapter.
177  */
178 static void CALESecureReceiveDataCB(const CASecureEndpoint_t *sep,
179                                  const void *data, size_t dataLen);
180
181 /**
182  * Callback to receive encrypted data from the ssl adapter.
183  */
184 static ssize_t CALESecureSendDataCB(CAEndpoint_t *endpoint,
185                              const void *data, size_t dataLen);
186 #endif
187
188
189 /**
190  * Register network change notification callback.
191  *
192  * @param[in]  netCallback  CAAdapterChangeCallback callback which will
193  *                          be set for the change in adapter.
194  * @param[in]  connCallback CAConnectionChangeCallback callback which will
195  *                          be set for the change in connection.
196  *
197  * @return  0 on success otherwise a positive error value.
198  * @retval  ::CA_STATUS_OK  Successful.
199  * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
200  * @retval  ::CA_STATUS_FAILED Operation failed.
201  *
202  */
203 static CAResult_t CALERegisterNetworkNotifications(CAAdapterChangeCallback netCallback,
204                                                    CAConnectionChangeCallback connCallback);
205
206 /**
207  * Set the thread pool handle which is required for spawning new
208  * thread.
209  *
210  * @param[in] handle Thread pool handle which is given by above layer
211  *                   for using thread creation task.
212  *
213  */
214 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle);
215
216 /**
217  * Call the callback to the upper layer when the adapter state gets
218  * changed.
219  *
220  * @param[in] adapter_state New state of the adapter to be notified to
221  *                          the upper layer.
222  */
223 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state);
224
225 /**
226  * Call the callback to the upper layer when the device connection state gets
227  * changed.
228  *
229  * @param[in] address      LE address of the device to be notified to the upper layer.
230  * @param[in] isConnected  whether connection state is connected or not.
231  */
232 static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const char* address,
233                                          bool isConnected);
234
235 /**
236  * Used to initialize all required mutex variable for LE Adapter
237  * implementation.
238  *
239  * @return  0 on success otherwise a positive error value.
240  * @retval  ::CA_STATUS_OK  Successful.
241  * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
242  * @retval  ::CA_STATUS_FAILED Operation failed.
243  *
244  */
245 static CAResult_t CAInitLEAdapterMutex();
246
247 /**
248  * Terminate all required mutex variables for LE adapter
249  * implementation.
250  */
251 static void CATerminateLEAdapterMutex();
252
253 /**
254  * Prepares and notify error through error callback.
255  */
256 static void CALEErrorHandler(const char *remoteAddress,
257                              const uint8_t *data,
258                              uint32_t dataLen,
259                              CAResult_t result);
260
261 /**
262  * Stop condition of Server recvhandler.
263  */
264 static bool g_dataBleServerReceiverHandlerState = false;
265
266 /**
267  * Stop condition of Client recvhandler.
268  */
269 static bool g_dataBleClientReceiverHandlerState = false;
270
271 /**
272  * Sender information of Server.
273  */
274 static u_arraylist_t *g_bleServerSenderInfo = NULL;
275
276 /**
277  * Sender information of Client.
278  */
279 static u_arraylist_t *g_bleClientSenderInfo = NULL;
280
281 /**
282  * Queue to process the outgoing packets from GATTServer.
283  */
284 static CAQueueingThread_t *g_bleServerSendQueueHandle = NULL;
285
286 /**
287  * Queue to process the outgoing packets from GATTClient.
288  */
289 static CAQueueingThread_t *g_bleClientSendQueueHandle = NULL;
290
291 /**
292  * Queue to process the incoming packets from GATTServer.
293  */
294 static CAQueueingThread_t *g_bleServerReceiverQueue = NULL;
295
296 /**
297  * Queue to process the incoming packets from GATTClient.
298  */
299 static CAQueueingThread_t *g_bleClientReceiverQueue = NULL;
300
301 /**
302  * This function will be associated with the sender queue for
303  * GattClient.
304  *
305  * This function will fragment the data to the MTU of the transport
306  * and send the data in fragments to the adapters. The function will
307  * be blocked until all data is sent out from the adapter.
308  *
309  * @param[in] threadData Data pushed to the queue which contains the
310  *                       info about RemoteEndpoint and Data.
311  */
312 static void CALEClientSendDataThread(void *threadData);
313
314 /**
315  * This function will defragment the received data from each sender
316  * respectively and will send it up to CA layer.  Respective sender's
317  * header will provide the length of the data sent.
318  *
319  * @param[in] threadData   Data pushed to the queue which contains the
320  *                         info about RemoteEndpoint and Data.
321  * @param[in] receiverType Whether receiver is server or client.
322  */
323 static void CALEDataReceiverHandler(void *threadData, CABLEAdapter_t receiverType);
324
325 /**
326  * This function will be associated with the receiver queue for
327  * GattClient.
328  *
329  * This function will call the function CALEDataReceiverHandler()
330  * with client type to defragment the received data.
331  *
332  * @param[in] threadData Data pushed to the queue which contains the
333  *                       info about RemoteEndpoint and Data.
334  */
335 static void CALEClientDataReceiverHandler(void *threadData);
336
337 /**
338  * This function will stop all queues created for GattServer and
339  * GattClient. All four queues will be be stopped with this function
340  * invocations.
341  */
342 static void CAStopLEQueues();
343
344 /**
345  * This function will terminate all queues created for GattServer and
346  * GattClient. All four queues will be be terminated with this
347  * function invocations.
348  */
349 static void CATerminateLEQueues();
350
351 #if !defined(ROUTING_GATEWAY) && !defined(SINGLE_THREAD)
352 /**
353  * This function will be associated with the sender queue for
354  * GattServer.
355  *
356  * This function will fragment the data to the MTU of the transport
357  * and send the data in fragments to the adapters. The function will
358  * be blocked until all data is sent out from the adapter.
359  *
360  * @param[in] threadData Data pushed to the queue which contains the
361  *                       info about RemoteEndpoint and Data.
362  */
363 static void CALEServerSendDataThread(void *threadData);
364
365 /**
366  * This function will be associated with the receiver queue for
367  * GattServer.
368  *
369  * This function will call the function CALEDataReceiverHandler()
370  * with server type to defragment the received data.
371  *
372  * @param[in] threadData Data pushed to the queue which contains the
373  *                       info about RemoteEndpoint and Data.
374  */
375 static void CALEServerDataReceiverHandler(void *threadData);
376
377 /**
378  * This function will initalize the Receiver and Sender queues for
379  * GattServer. This function will in turn call the functions
380  * CAInitBleServerReceiverQueue() and CAInitBleServerSenderQueue() to
381  * initialize the queues.
382  *
383  * @return ::CA_STATUS_OK or Appropriate error code.
384  * @retval ::CA_STATUS_OK  Successful.
385  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
386  * @retval ::CA_STATUS_FAILED Operation failed.
387  */
388 static CAResult_t CAInitLEServerQueues();
389
390 /**
391  * This function will initalize the Receiver queue for
392  * GattServer. This will initialize the queue to process the function
393  * CABLEServerSendDataThread() when ever the task is added to this
394  * queue.
395  *
396  * @return ::CA_STATUS_OK or Appropriate error code.
397  * @retval ::CA_STATUS_OK  Successful.
398  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
399  * @retval ::CA_STATUS_FAILED Operation failed.
400  */
401 static CAResult_t CAInitLEServerSenderQueue();
402
403 /**
404  * This function will initialize the Receiver queue for
405  * GattServer. This will initialize the queue to process the function
406  * CALEServerDataReceiverHandler() when ever the task is added to this
407  * queue.
408  *
409  * @return ::CA_STATUS_OK or Appropriate error code
410  * @retval ::CA_STATUS_OK  Successful
411  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments
412  * @retval ::CA_STATUS_FAILED Operation failed
413  *
414  */
415 static CAResult_t CAInitLEServerReceiverQueue();
416 #endif // not ROUTING_GATEWAY not SINGLE_THREAD
417
418 /**
419  * This function will initalize the Receiver and Sender queues for
420  * GattClient. This function will inturn call the functions
421  * CAInitBleClientReceiverQueue() and CAInitBleClientSenderQueue() to
422  * initialize the queues.
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  */
430 static CAResult_t CAInitLEClientQueues();
431
432 /**
433  * This function will initalize the Receiver queue for
434  * GattClient. This will initialize the queue to process the function
435  * CABLEClientSendDataThread() when ever the task is added to this
436  * queue.
437  *
438  * @return ::CA_STATUS_OK or Appropriate error code.
439  * @retval ::CA_STATUS_OK  Successful.
440  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
441  * @retval ::CA_STATUS_FAILED Operation failed.
442  */
443 static CAResult_t CAInitLEClientSenderQueue();
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 /**
492  * remove request or response data of send queue.
493  *
494  * @param[in] queueHandle    queue to process the outgoing packets.
495  * @param[in] mutex          mutex related to sender for client / server.
496  * @param[in] address        target address to remove data in queue.
497  */
498 static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle,
499                                     oc_mutex mutex,
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 serderInfo.
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                                     size_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
542 static CAResult_t CAInitLEClientQueues()
543 {
544     oc_mutex_lock(g_bleAdapterThreadPoolMutex);
545
546     CAResult_t result = CAInitLEClientSenderQueue();
547     if (CA_STATUS_OK != result)
548     {
549         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientSenderQueue failed");
550         oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
551         return CA_STATUS_FAILED;
552     }
553
554     g_bleClientSenderInfo = u_arraylist_create();
555     if (!g_bleClientSenderInfo)
556     {
557         OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
558         oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
559         return CA_MEMORY_ALLOC_FAILED;
560     }
561
562     result = CAInitLEClientReceiverQueue();
563     if (CA_STATUS_OK != result)
564     {
565         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientReceiverQueue failed");
566         u_arraylist_free(&g_bleClientSenderInfo);
567         oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
568         return CA_STATUS_FAILED;
569     }
570
571     g_dataBleClientReceiverHandlerState = true;
572
573     oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
574     return CA_STATUS_OK;
575 }
576
577 static CAResult_t CAInitLEClientReceiverQueue()
578 {
579     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAInitLEClientReceiverQueue");
580     // Check if the message queue is already initialized
581     if (g_bleClientReceiverQueue)
582     {
583         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
584         return CA_STATUS_OK;
585     }
586
587     // Create recv message queue
588     g_bleClientReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
589     if (!g_bleClientReceiverQueue)
590     {
591         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
592         return CA_MEMORY_ALLOC_FAILED;
593     }
594
595     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientReceiverQueue,
596                                                    g_bleAdapterThreadPool,
597                                                    CALEClientDataReceiverHandler,
598                                                    CALEDataDestroyer))
599     {
600         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize client receiver queue thread");
601         OICFree(g_bleClientReceiverQueue);
602         g_bleClientReceiverQueue = NULL;
603         return CA_STATUS_FAILED;
604     }
605
606     if (CA_STATUS_OK != CAQueueingThreadStart(g_bleClientReceiverQueue))
607     {
608         OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
609         OICFree(g_bleClientReceiverQueue);
610         g_bleClientReceiverQueue = NULL;
611         return CA_STATUS_FAILED;
612     }
613
614     return CA_STATUS_OK;
615 }
616
617 #if !defined(ROUTING_GATEWAY) && !defined(SINGLE_THREAD)
618 static CAResult_t CAInitLEServerQueues()
619 {
620     oc_mutex_lock(g_bleAdapterThreadPoolMutex);
621
622     CAResult_t result = CAInitLEServerSenderQueue();
623     if (CA_STATUS_OK != result)
624     {
625         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerSenderQueue failed");
626         oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
627         return CA_STATUS_FAILED;
628     }
629
630     g_bleServerSenderInfo = u_arraylist_create();
631     if (!g_bleServerSenderInfo)
632     {
633         OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
634         oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
635         return CA_MEMORY_ALLOC_FAILED;
636     }
637
638     result = CAInitLEServerReceiverQueue();
639     if (CA_STATUS_OK != result)
640     {
641         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerReceiverQueue failed");
642         u_arraylist_free(&g_bleServerSenderInfo);
643         oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
644         return CA_STATUS_FAILED;
645     }
646
647     g_dataBleServerReceiverHandlerState = true;
648
649     oc_mutex_unlock(g_bleAdapterThreadPoolMutex);
650     return CA_STATUS_OK;
651 }
652
653 static CAResult_t CAInitLEServerReceiverQueue()
654 {
655     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAInitLEServerReceiverQueue");
656     // Check if the message queue is already initialized
657     if (g_bleServerReceiverQueue)
658     {
659         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
660         return CA_STATUS_OK;
661     }
662
663     // Create recv message queue
664     g_bleServerReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
665     if (!g_bleServerReceiverQueue)
666     {
667         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
668         return CA_MEMORY_ALLOC_FAILED;
669     }
670
671     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerReceiverQueue,
672                                                    g_bleAdapterThreadPool,
673                                                    CALEServerDataReceiverHandler,
674                                                    CALEDataDestroyer))
675     {
676         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize server receiver queue thread");
677         OICFree(g_bleServerReceiverQueue);
678         g_bleServerReceiverQueue = NULL;
679         return CA_STATUS_FAILED;
680     }
681
682     if (CA_STATUS_OK != CAQueueingThreadStart(g_bleServerReceiverQueue))
683     {
684         OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
685         OICFree(g_bleServerReceiverQueue);
686         g_bleServerReceiverQueue = NULL;
687         return CA_STATUS_FAILED;
688     }
689
690     return CA_STATUS_OK;
691 }
692
693 static CAResult_t CAInitLEServerSenderQueue()
694 {
695     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAInitLEServerSenderQueue");
696     // Check if the message queue is already initialized
697     if (g_bleServerSendQueueHandle)
698     {
699         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Queue is already initialized!");
700         return CA_STATUS_OK;
701     }
702
703     // Create send message queue
704     g_bleServerSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
705     if (!g_bleServerSendQueueHandle)
706     {
707         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
708         return CA_MEMORY_ALLOC_FAILED;
709     }
710
711     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerSendQueueHandle,
712                                                    g_bleAdapterThreadPool,
713                                                    CALEServerSendDataThread,
714                                                    CALEDataDestroyer))
715     {
716         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
717         OICFree(g_bleServerSendQueueHandle);
718         g_bleServerSendQueueHandle = NULL;
719         return CA_STATUS_FAILED;
720     }
721
722     return CA_STATUS_OK;
723 }
724
725 static void CALEServerDataReceiverHandler(void *threadData)
726 {
727     CALEDataReceiverHandler(threadData, ADAPTER_SERVER);
728 }
729
730 static void CALEServerSendDataThread(void *threadData)
731 {
732     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEServerSendDataThread");
733
734     CALEData_t * const bleData = (CALEData_t *) threadData;
735     if (!bleData)
736     {
737         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bledata!");
738         return;
739     }
740
741     if (!bleData->remoteEndpoint)
742     {
743         OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid endpoint of bledata!");
744         return;
745     }
746
747 #if defined(__TIZEN__) || defined(__ANDROID__)
748     // get MTU size
749     g_mtuSize = CALEServerGetMtuSize(bleData->remoteEndpoint->addr);
750 #endif
751     OIC_LOG_V(INFO, CALEADAPTER_TAG, "MTU size [%d]", g_mtuSize);
752
753     uint32_t midPacketCount = 0;
754     size_t remainingLen = 0;
755     size_t totalLength = 0;
756     CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
757
758     CAResult_t result = CAGenerateVariableForFragmentation(bleData->dataLen,
759                                                            &midPacketCount,
760                                                            &remainingLen,
761                                                            &totalLength,
762                                                            g_mtuSize);
763
764     if (CA_STATUS_OK != result)
765     {
766         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
767                   "CAGenerateVariableForFragmentation failed, result [%d]", result);
768         if (g_errorHandler)
769         {
770             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
771         }
772         return;
773     }
774
775     OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
776               "Packet info: data size[%d] midPacketCount[%u] remainingLen[%" PRIuPTR "] totalLength[%" PRIuPTR "]",
777               bleData->dataLen, midPacketCount, remainingLen, totalLength);
778
779     OIC_LOG_V(DEBUG,
780               CALEADAPTER_TAG,
781               "Server total Data length with header is [%" PRIuPTR "]",
782               totalLength);
783
784     uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
785     uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
786
787     if (NULL != bleData->remoteEndpoint) //Unicast Data
788     {
789         secureFlag = (bleData->remoteEndpoint->flags & CA_SECURE) ?
790             CA_BLE_PACKET_SECURE : CA_BLE_PACKET_NON_SECURE;
791
792         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This Packet is secure? %d", secureFlag);
793         result = CAGenerateHeader(dataHeader,
794                                   CA_BLE_PACKET_START,
795                                   g_localBLESourcePort,
796                                   secureFlag,
797                                   bleData->remoteEndpoint->port);
798     }
799     else                                //Multicast Data
800     {
801         result = CAGenerateHeader(dataHeader,
802                                   CA_BLE_PACKET_START,
803                                   g_localBLESourcePort,
804                                   secureFlag,
805                                   CA_BLE_MULTICAST_PORT);
806     }
807
808     if (CA_STATUS_OK != result)
809     {
810         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
811                   "CAGenerateHeader failed, result [%d]", result);
812         if (g_errorHandler)
813         {
814             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
815         }
816         return;
817     }
818
819     uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
820     result = CAGenerateHeaderPayloadLength(lengthHeader,
821                                            CA_BLE_LENGTH_HEADER_SIZE,
822                                            bleData->dataLen);
823
824     if (CA_STATUS_OK != result)
825     {
826         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
827                   "CAGenerateHeaderPayloadLength failed, result [%d]", result);
828         if (g_errorHandler)
829         {
830             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
831         }
832         return;
833     }
834
835     uint32_t length = 0;
836     uint32_t dataLen = 0;
837     if (g_mtuSize > totalLength)
838     {
839         length = totalLength;
840         dataLen = bleData->dataLen;
841     }
842     else
843     {
844         length = g_mtuSize;
845         dataLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
846     }
847
848     result = CAMakeFirstDataSegment(dataSegment,
849                                     bleData->data, dataLen,
850                                     dataHeader, lengthHeader);
851
852     if (CA_STATUS_OK != result)
853     {
854         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
855                   "Making data segment failed, result [%d]", result);
856         if (g_errorHandler)
857         {
858             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
859         }
860         return;
861     }
862
863     const uint32_t iter = midPacketCount;
864     uint32_t index = 0;
865
866     // Send the first segment with the header.
867     if (NULL != bleData->remoteEndpoint) // Sending Unicast Data
868     {
869         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Unicast Data");
870
871         result = CAUpdateCharacteristicsToGattClient(
872                     bleData->remoteEndpoint->addr, dataSegment, length);
873
874         if (CA_STATUS_OK != result)
875         {
876             OIC_LOG_V(ERROR,
877                       CALEADAPTER_TAG,
878                       "Update characteristics failed, result [%d]",
879                       result);
880             if (g_errorHandler)
881             {
882                 g_errorHandler(bleData->remoteEndpoint,
883                                bleData->data,
884                                bleData->dataLen,
885                                result);
886             }
887             return;
888         }
889
890         OIC_LOG_V(DEBUG,
891                   CALEADAPTER_TAG,
892                   "Server Sent Unicast First Data - data length [%u]",
893                   length);
894
895         result = CAGenerateHeader(dataHeader,
896                                   CA_BLE_PACKET_NOT_START,
897                                   g_localBLESourcePort,
898                                   secureFlag,
899                                   bleData->remoteEndpoint->port);
900
901         if (CA_STATUS_OK != result)
902         {
903             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
904                       "CAGenerateHeader failed, result [%d]", result);
905             if (g_errorHandler)
906             {
907                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
908             }
909             return;
910         }
911
912         for (index = 0; index < iter; index++)
913         {
914             // Send the remaining header.
915             result = CAMakeRemainDataSegment(dataSegment,
916                                              g_mtuSize - CA_BLE_HEADER_SIZE,
917                                              bleData->data,
918                                              bleData->dataLen,
919                                              index,
920                                              dataHeader,
921                                              g_mtuSize);
922
923             if (CA_STATUS_OK != result)
924             {
925                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
926                             "Making data segment failed, result [%d]", result);
927                 if (g_errorHandler)
928                 {
929                     g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
930                 }
931                 return;
932             }
933
934             result =
935                 CAUpdateCharacteristicsToGattClient(
936                     bleData->remoteEndpoint->addr,
937                     dataSegment,
938                     g_mtuSize);
939
940             if (CA_STATUS_OK != result)
941             {
942                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
943                             "Update characteristics failed, result [%d]", result);
944                 if (g_errorHandler)
945                 {
946                     g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
947                 }
948                 return;
949             }
950             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]",
951                                                g_mtuSize);
952         }
953
954         if (remainingLen && (totalLength > g_mtuSize))
955         {
956             // send the last segment of the data (Ex: 22 bytes of 622
957             // bytes of data when MTU is 200)
958             result = CAMakeRemainDataSegment(dataSegment,
959                                              remainingLen,
960                                              bleData->data,
961                                              bleData->dataLen,
962                                              index,
963                                              dataHeader,
964                                              g_mtuSize);
965
966             if (CA_STATUS_OK != result)
967             {
968                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
969                             "Making data segment failed, result [%d]", result);
970                 if (g_errorHandler)
971                 {
972                     g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
973                 }
974                 return;
975             }
976
977             result = CAUpdateCharacteristicsToGattClient(
978                          bleData->remoteEndpoint->addr,
979                          dataSegment,
980                          remainingLen + CA_BLE_HEADER_SIZE);
981
982             if (CA_STATUS_OK != result)
983             {
984                 OIC_LOG_V(ERROR,
985                           CALEADAPTER_TAG,
986                           "Update characteristics failed, result [%d]",
987                           result);
988                 if (g_errorHandler)
989                 {
990                     g_errorHandler(bleData->remoteEndpoint,
991                                    bleData->data,
992                                    bleData->dataLen,
993                                    result);
994                 }
995                 return;
996             }
997             OIC_LOG_V(DEBUG,
998                       CALEADAPTER_TAG,
999                       "Server Sent Unicast Last Data - data length [%" PRIuPTR "]",
1000                       remainingLen + CA_BLE_HEADER_SIZE);
1001         }
1002      }
1003     else
1004     {
1005         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
1006 #if defined(__TIZEN__)
1007         // @todo
1008         // tizen ble should also disabled when Tizen 3.0 is updated.
1009         result = CAUpdateCharacteristicsToAllGattClients(dataSegment, length);
1010         if (CA_STATUS_OK != result)
1011         {
1012             OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1013                       result);
1014             CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1015             return;
1016         }
1017
1018         result = CAGenerateHeader(dataHeader,
1019                                   CA_BLE_PACKET_NOT_START,
1020                                   g_localBLESourcePort,
1021                                   secureFlag,
1022                                   CA_BLE_MULTICAST_PORT);
1023
1024         if (CA_STATUS_OK != result)
1025         {
1026             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1027                       "CAGenerateHeader failed, result [%d]", result);
1028             if (g_errorHandler)
1029             {
1030                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1031             }
1032             return;
1033         }
1034         OIC_LOG_V(DEBUG,
1035                   CALEADAPTER_TAG,
1036                   "Server Sent Multicast First Data - data length [%zu]",
1037                   length);
1038
1039         for (index = 0; index < iter; index++)
1040         {
1041             // Send the remaining header.
1042             result = CAMakeRemainDataSegment(dataSegment,
1043                                              CA_BLE_NORMAL_SEGMENT_PAYLOAD_SIZE,
1044                                              bleData->data,
1045                                              bleData->dataLen,
1046                                              index,
1047                                              dataHeader);
1048
1049             if (CA_STATUS_OK != result)
1050             {
1051                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1052                             "Making data segment failed, result [%d]", result);
1053                 if (g_errorHandler)
1054                 {
1055                     g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1056                 }
1057                 return;
1058             }
1059
1060             result = CAUpdateCharacteristicsToAllGattClients(
1061                          dataSegment,
1062                          CA_SUPPORTED_BLE_MTU_SIZE);
1063
1064             if (CA_STATUS_OK != result)
1065             {
1066                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1067                           result);
1068                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1069                 return;
1070             }
1071             OIC_LOG_V(DEBUG,
1072                       CALEADAPTER_TAG,
1073                       "Server Sent Multicast %d Data - data length [%zu]",
1074                       index + 1,
1075                       CA_SUPPORTED_BLE_MTU_SIZE);
1076         }
1077
1078         if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
1079         {
1080             // send the last segment of the data (Ex: 22 bytes of 622
1081             // bytes of data when MTU is 200)
1082             result = CAMakeRemainDataSegment(dataSegment,
1083                                              remainingLen,
1084                                              bleData->data,
1085                                              bleData->dataLen,
1086                                              index,
1087                                              dataHeader);
1088
1089             if (CA_STATUS_OK != result)
1090             {
1091                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1092                             "Making data segment failed, result [%d]", result);
1093                 if (g_errorHandler)
1094                 {
1095                     g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1096                 }
1097                 return;
1098             }
1099
1100             result = CAUpdateCharacteristicsToAllGattClients(
1101                          dataSegment,
1102                          remainingLen + CA_BLE_HEADER_SIZE);
1103
1104             if (CA_STATUS_OK != result)
1105             {
1106                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1107                           result);
1108                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1109                 return;
1110             }
1111             OIC_LOG_V(DEBUG,
1112                       CALEADAPTER_TAG,
1113                       "Server Sent Multicast Last Data - data length [%" PRIuPTR "]",
1114                       remainingLen + CA_BLE_HEADER_SIZE);
1115         }
1116 #else
1117         OIC_LOG(DEBUG, CALEADAPTER_TAG, "BLE Multicast is not supported");
1118 #endif
1119     }
1120
1121     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CALEServerSendDataThread");
1122 }
1123 #endif // not ROUTING_GATEWAY not SINGLE_THREAD
1124
1125 static void CALEClearSenderInfoImpl(u_arraylist_t ** list)
1126 {
1127     const size_t length = u_arraylist_length(*list);
1128     for (size_t i = 0; i < length; ++i)
1129     {
1130         CABLESenderInfo_t * const info =
1131                 (CABLESenderInfo_t *) u_arraylist_get(*list, i);
1132         if (info)
1133          {
1134              OICFree(info->defragData);
1135              CAFreeEndpoint(info->remoteEndpoint);
1136              OICFree(info);
1137          }
1138     }
1139     u_arraylist_free(list);
1140 }
1141
1142 static void CALEClearSenderInfo()
1143 {
1144     CALEClearSenderInfoImpl(&g_bleServerSenderInfo);
1145     CALEClearSenderInfoImpl(&g_bleClientSenderInfo);
1146 }
1147
1148 static CAResult_t CAInitLEClientSenderQueue()
1149 {
1150     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAInitLEClientSenderQueue");
1151
1152     if (g_bleClientSendQueueHandle)
1153     {
1154         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
1155         return CA_STATUS_OK;
1156     }
1157
1158     // Create send message queue
1159     g_bleClientSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
1160     if (!g_bleClientSendQueueHandle)
1161     {
1162         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1163         return CA_MEMORY_ALLOC_FAILED;
1164     }
1165
1166     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientSendQueueHandle,
1167                                                    g_bleAdapterThreadPool,
1168                                                    CALEClientSendDataThread, CALEDataDestroyer))
1169     {
1170         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
1171         OICFree(g_bleClientSendQueueHandle);
1172         g_bleClientSendQueueHandle = NULL;
1173         return CA_STATUS_FAILED;
1174     }
1175     return CA_STATUS_OK;
1176 }
1177
1178 static void CAStopLEQueues()
1179 {
1180     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAStopLEQueues");
1181
1182     oc_mutex_lock(g_bleServerReceiveDataMutex);
1183     if (NULL != g_bleServerReceiverQueue)
1184     {
1185         CAQueueingThreadStop(g_bleServerReceiverQueue);
1186     }
1187     oc_mutex_unlock(g_bleServerReceiveDataMutex);
1188
1189     oc_mutex_lock(g_bleClientReceiveDataMutex);
1190     if (NULL != g_bleClientReceiverQueue)
1191     {
1192         CAQueueingThreadStop(g_bleClientReceiverQueue);
1193     }
1194     oc_mutex_unlock(g_bleClientReceiveDataMutex);
1195
1196     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CAStopLEQueues");
1197 }
1198
1199 static void CATerminateLEQueues()
1200 {
1201     CAQueueingThreadDestroy(g_bleClientSendQueueHandle);
1202     OICFree(g_bleClientSendQueueHandle);
1203     g_bleClientSendQueueHandle = NULL;
1204
1205     CAQueueingThreadDestroy(g_bleServerSendQueueHandle);
1206     OICFree(g_bleServerSendQueueHandle);
1207     g_bleServerSendQueueHandle = NULL;
1208
1209     CAQueueingThreadDestroy(g_bleServerReceiverQueue);
1210     OICFree(g_bleServerReceiverQueue);
1211     g_bleServerReceiverQueue = NULL;
1212
1213     CAQueueingThreadDestroy(g_bleClientReceiverQueue);
1214     OICFree(g_bleClientReceiverQueue);
1215     g_bleClientReceiverQueue = NULL;
1216
1217     CALEClearSenderInfo();
1218 }
1219
1220 static CAResult_t CALEGetSenderInfo(const char *leAddress,
1221                                     const uint16_t port,
1222                                     u_arraylist_t *senderInfoList,
1223                                     CABLESenderInfo_t **senderInfo,
1224                                     size_t *senderIndex)
1225 {
1226     VERIFY_NON_NULL_RET(leAddress,
1227                         CALEADAPTER_TAG,
1228                         "NULL BLE address argument",
1229                         CA_STATUS_INVALID_PARAM);
1230     VERIFY_NON_NULL_RET(senderIndex,
1231                         CALEADAPTER_TAG,
1232                         "NULL index argument",
1233                         CA_STATUS_INVALID_PARAM);
1234
1235     const size_t listLength = u_arraylist_length(senderInfoList);
1236     const size_t addrLength = strlen(leAddress);
1237     for (size_t index = 0; index < listLength; index++)
1238     {
1239         CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(senderInfoList, index);
1240         if (!info || !(info->remoteEndpoint))
1241         {
1242             continue;
1243         }
1244
1245         if (!strncmp(info->remoteEndpoint->addr, leAddress, addrLength))
1246         {
1247             if (info->remoteEndpoint->port == port)
1248             {
1249                 *senderIndex = index;
1250                 if (senderInfo)
1251                 {
1252                     *senderInfo = info;
1253                 }
1254                 return CA_STATUS_OK;
1255             }
1256         }
1257     }
1258
1259     return CA_STATUS_FAILED;
1260 }
1261
1262 static void CALEDataReceiverHandler(void *threadData, CABLEAdapter_t receiverType)
1263 {
1264     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEDataReceiverHandler");
1265
1266     oc_mutex bleReceiveDataMutex = NULL;
1267     bool dataBleReceiverHandlerState = false;
1268 #ifdef __WITH_DTLS__
1269     CADataType_t dataType = CA_REQUEST_DATA;
1270 #endif
1271
1272     switch (receiverType)
1273     {
1274         case ADAPTER_CLIENT:
1275             bleReceiveDataMutex = g_bleClientReceiveDataMutex;
1276             dataBleReceiverHandlerState = g_dataBleClientReceiverHandlerState;
1277 #ifdef __WITH_DTLS__
1278             dataType = CA_REQUEST_DATA;
1279 #endif
1280             break;
1281         case ADAPTER_SERVER:
1282             bleReceiveDataMutex = g_bleServerReceiveDataMutex;
1283             dataBleReceiverHandlerState = g_dataBleServerReceiverHandlerState;
1284 #ifdef __WITH_DTLS__
1285             dataType = CA_RESPONSE_DATA;
1286 #endif
1287             break;
1288         default:
1289             OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Unsupported receiver type : %d", receiverType);
1290             return;
1291     }
1292
1293     oc_mutex_lock(bleReceiveDataMutex);
1294
1295     if (dataBleReceiverHandlerState)
1296     {
1297         CALEData_t *bleData = (CALEData_t *) threadData;
1298         if (!bleData)
1299         {
1300             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bleData!");
1301             oc_mutex_unlock(bleReceiveDataMutex);
1302             return;
1303         }
1304
1305         if (!(bleData->senderInfo))
1306         {
1307             OIC_LOG(ERROR, CALEADAPTER_TAG, "sender info is not available");
1308             oc_mutex_unlock(bleReceiveDataMutex);
1309             return;
1310         }
1311
1312         if (!(bleData->remoteEndpoint))
1313         {
1314             OIC_LOG(ERROR, CALEADAPTER_TAG, "RemoteEndPoint NULL!!");
1315             oc_mutex_unlock(bleReceiveDataMutex);
1316             return;
1317         }
1318
1319         CABLESenderInfo_t *senderInfo = NULL;
1320         size_t senderIndex = 0;
1321
1322         //packet parsing
1323         CABLEPacketStart_t startFlag = CA_BLE_PACKET_NOT_START;
1324         CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1325         uint16_t sourcePort = 0;
1326         uint16_t destPort = 0;
1327
1328         CAParseHeader(bleData->data, &startFlag, &sourcePort, &secureFlag, &destPort);
1329         OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1330                   "header info: startFlag[%X] sourcePort[%d] secureFlag[%X] destPort[%d]",
1331                   startFlag, sourcePort, secureFlag, destPort);
1332
1333         if (destPort != g_localBLESourcePort && destPort != CA_BLE_MULTICAST_PORT)
1334         {
1335             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1336                       "this packet is not valid for this app(port mismatch[mine:%d, packet:%d])",
1337                       g_localBLESourcePort, destPort);
1338             oc_mutex_unlock(bleReceiveDataMutex);
1339             return;
1340         }
1341
1342         bleData->remoteEndpoint->port = sourcePort;
1343
1344         if (CA_STATUS_OK != CALEGetSenderInfo(bleData->remoteEndpoint->addr,
1345                                               bleData->remoteEndpoint->port,
1346                                               bleData->senderInfo,
1347                                               &senderInfo, &senderIndex))
1348         {
1349             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This is a new client [%s:%X]",
1350                       bleData->remoteEndpoint->addr, bleData->remoteEndpoint->port);
1351         }
1352         else
1353         {
1354             if (startFlag)
1355             {
1356                 OIC_LOG(ERROR, CALEADAPTER_TAG,
1357                         "This packet is start packet but exist senderInfo. Remove senderInfo");
1358                 u_arraylist_remove(bleData->senderInfo, senderIndex);
1359                 OICFree(senderInfo->defragData);
1360                 OICFree(senderInfo);
1361                 senderInfo = NULL;
1362                 senderIndex = 0;
1363             }
1364         }
1365
1366         if (!senderInfo)
1367         {
1368             uint32_t totalLength = 0;
1369             if (startFlag)
1370             {
1371                 CAParseHeaderPayloadLength(bleData->data, CA_BLE_LENGTH_HEADER_SIZE, &totalLength);
1372             }
1373             else
1374             {
1375                 OIC_LOG(ERROR, CALEADAPTER_TAG, "This packet is wrong packet! ignore.");
1376                 oc_mutex_unlock(bleReceiveDataMutex);
1377                 return;
1378             }
1379
1380             CABLESenderInfo_t *newSender = OICMalloc(sizeof(CABLESenderInfo_t));
1381             if (!newSender)
1382             {
1383                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed for new sender");
1384                 oc_mutex_unlock(bleReceiveDataMutex);
1385                 return;
1386             }
1387             newSender->recvDataLen = 0;
1388             newSender->totalDataLen = 0;
1389             newSender->defragData = NULL;
1390             newSender->remoteEndpoint = NULL;
1391
1392             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
1393
1394             newSender->totalDataLen = totalLength;
1395
1396             if (!(newSender->totalDataLen))
1397             {
1398                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Total Data Length is parsed as 0!!!");
1399                 OICFree(newSender);
1400                 oc_mutex_unlock(bleReceiveDataMutex);
1401                 return;
1402             }
1403
1404             size_t dataOnlyLen =
1405                 bleData->dataLen - (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE);
1406             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%u] bytes",
1407                       newSender->totalDataLen);
1408             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "data received in the first packet [%" PRIuPTR "] bytes",
1409                       dataOnlyLen);
1410
1411             newSender->defragData = OICCalloc(newSender->totalDataLen + 1,
1412                                               sizeof(*newSender->defragData));
1413
1414             if (NULL == newSender->defragData)
1415             {
1416                 OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
1417                 OICFree(newSender);
1418                 oc_mutex_unlock(bleReceiveDataMutex);
1419                 return;
1420             }
1421             CATransportFlags_t flags = CA_DEFAULT_FLAGS;
1422 #ifdef __WITH_DTLS__
1423             if (CA_BLE_PACKET_SECURE ==  secureFlag)
1424             {
1425                 flags |= CA_SECURE;
1426             }
1427 #endif
1428
1429             const char *remoteAddress = bleData->remoteEndpoint->addr;
1430             newSender->remoteEndpoint = CACreateEndpointObject(flags,
1431                                                                CA_ADAPTER_GATT_BTLE,
1432                                                                remoteAddress,
1433                                                                bleData->remoteEndpoint->port);
1434
1435             if (NULL == newSender->remoteEndpoint)
1436             {
1437                 OIC_LOG(ERROR, CALEADAPTER_TAG, "remoteEndpoint is NULL!");
1438                 OICFree(newSender->defragData);
1439                 OICFree(newSender);
1440                 oc_mutex_unlock(bleReceiveDataMutex);
1441                 return;
1442             }
1443
1444             if (newSender->recvDataLen + dataOnlyLen > newSender->totalDataLen)
1445             {
1446                 OIC_LOG(ERROR, CALEADAPTER_TAG, "buffer is smaller than received data");
1447                 OICFree(newSender->defragData);
1448                 CAFreeEndpoint(newSender->remoteEndpoint);
1449                 OICFree(newSender);
1450                 oc_mutex_unlock(bleReceiveDataMutex);
1451                 return;
1452             }
1453             memcpy(newSender->defragData,
1454                    bleData->data + (CA_BLE_HEADER_SIZE + CA_BLE_LENGTH_HEADER_SIZE),
1455                    dataOnlyLen);
1456             newSender->recvDataLen += dataOnlyLen;
1457
1458             u_arraylist_add(bleData->senderInfo,(void *)newSender);
1459
1460             //Getting newSender index position in bleSenderInfo array list
1461             if (CA_STATUS_OK !=
1462                     CALEGetSenderInfo(newSender->remoteEndpoint->addr,
1463                                       newSender->remoteEndpoint->port,
1464                                       bleData->senderInfo,
1465                                       NULL, &senderIndex))
1466             {
1467                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Existing sender index not found!!");
1468                 OICFree(newSender->defragData);
1469                 CAFreeEndpoint(newSender->remoteEndpoint);
1470                 OICFree(newSender);
1471                 oc_mutex_unlock(bleReceiveDataMutex);
1472                 return;
1473             }
1474             senderInfo = newSender;
1475         }
1476         else
1477         {
1478             size_t dataOnlyLen = bleData->dataLen - CA_BLE_HEADER_SIZE;
1479             if (senderInfo->recvDataLen + dataOnlyLen > senderInfo->totalDataLen)
1480             {
1481                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1482                           "Data Length exceeding error!! Receiving [%" PRIuPTR "] total length [%u]",
1483                           senderInfo->recvDataLen + dataOnlyLen, senderInfo->totalDataLen);
1484                 u_arraylist_remove(bleData->senderInfo, senderIndex);
1485                 OICFree(senderInfo->defragData);
1486                 OICFree(senderInfo);
1487                 oc_mutex_unlock(bleReceiveDataMutex);
1488                 return;
1489             }
1490             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%" PRIuPTR "]",
1491                       dataOnlyLen);
1492             memcpy(senderInfo->defragData + senderInfo->recvDataLen,
1493                    bleData->data + CA_BLE_HEADER_SIZE,
1494                    dataOnlyLen);
1495             senderInfo->recvDataLen += dataOnlyLen;
1496             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "totalDatalength  [%d] received Datalen [%d]",
1497                                                 senderInfo->totalDataLen, senderInfo->recvDataLen);
1498         }
1499
1500         if (senderInfo->totalDataLen == senderInfo->recvDataLen)
1501         {
1502             oc_mutex_lock(g_bleAdapterReqRespCbMutex);
1503             if (NULL == g_networkPacketReceivedCallback)
1504             {
1505                 OIC_LOG(ERROR, CALEADAPTER_TAG, "gReqRespCallback is NULL!");
1506
1507                 u_arraylist_remove(bleData->senderInfo, senderIndex);
1508                 OICFree(senderInfo->defragData);
1509                 OICFree(senderInfo);
1510                 oc_mutex_unlock(g_bleAdapterReqRespCbMutex);
1511                 oc_mutex_unlock(bleReceiveDataMutex);
1512                 return;
1513             }
1514
1515             OIC_LOG(DEBUG, CALEADAPTER_TAG, "[CALEDataReceiverHandler] Received data up !");
1516
1517             const CASecureEndpoint_t tmp =
1518                 {
1519                     .endpoint = *senderInfo->remoteEndpoint
1520                 };
1521
1522 #ifdef __WITH_DTLS__
1523             if (CA_SECURE & tmp.endpoint.flags)
1524             {
1525                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Secure data received");
1526                 g_dataType = dataType;
1527
1528                 if (CA_STATUS_FAILED == CAdecryptSsl(&tmp,
1529                                                 senderInfo->defragData,
1530                                                 senderInfo->recvDataLen))
1531                 {
1532                     OIC_LOG(ERROR, CALEADAPTER_TAG, "CAdecryptSsl failed");
1533                 }
1534                 else
1535                 {
1536                     OIC_LOG(ERROR, CALEADAPTER_TAG, "CAdecryptSsl successed");
1537                 }
1538                 OICFree(senderInfo->defragData);
1539             }
1540             else
1541             {
1542 #endif
1543                 OIC_LOG(DEBUG, CALEADAPTER_TAG, "Non-Secure data received");
1544                 g_networkPacketReceivedCallback(&tmp,
1545                                                 senderInfo->defragData,
1546                                                 senderInfo->recvDataLen);
1547 #ifdef __WITH_DTLS__
1548             }
1549 #endif
1550
1551             oc_mutex_unlock(g_bleAdapterReqRespCbMutex);
1552             u_arraylist_remove(bleData->senderInfo, senderIndex);
1553             senderInfo->remoteEndpoint = NULL;
1554             senderInfo->defragData = NULL;
1555             OICFree(senderInfo);
1556         }
1557     }
1558     oc_mutex_unlock(bleReceiveDataMutex);
1559 }
1560
1561 static void CALEClientDataReceiverHandler(void *threadData)
1562 {
1563     CALEDataReceiverHandler(threadData, ADAPTER_CLIENT);
1564 }
1565
1566 static void CALEClientSendDataThread(void *threadData)
1567 {
1568     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEClientSendDataThread");
1569
1570     CALEData_t *bleData = (CALEData_t *) threadData;
1571     if (!bleData)
1572     {
1573         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bledata!");
1574         return;
1575     }
1576
1577     if (!bleData->remoteEndpoint)
1578     {
1579         OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid endpoint of bledata!");
1580         return;
1581     }
1582
1583 #if defined(__ANDROID__)
1584     // get MTU size
1585     if (false == CALEClientIsConnected(bleData->remoteEndpoint->addr))
1586     {
1587         // triggering to gatt connect and MTU negotiation
1588         CAResult_t res = CALEClientSendNegotiationMessage(
1589                 bleData->remoteEndpoint->addr);
1590
1591         if (CA_STATUS_OK != res)
1592         {
1593             OIC_LOG_V(ERROR,
1594                       CALEADAPTER_TAG,
1595                       "CALEClientSendNegotiationMessage has failed, result [%d]",
1596                       res);
1597             if (g_errorHandler)
1598             {
1599                 g_errorHandler(bleData->remoteEndpoint,
1600                                bleData->data,
1601                                bleData->dataLen,
1602                                res);
1603             }
1604             return;
1605         }
1606     }
1607     g_mtuSize = CALEClientGetMtuSize(bleData->remoteEndpoint->addr);
1608 #endif
1609     OIC_LOG_V(INFO, CALEADAPTER_TAG, "MTU size [%d]", g_mtuSize);
1610
1611     uint32_t midPacketCount = 0;
1612     size_t remainingLen = 0;
1613     size_t totalLength = 0;
1614     CABLEPacketSecure_t secureFlag = CA_BLE_PACKET_NON_SECURE;
1615
1616     CAResult_t result = CAGenerateVariableForFragmentation(bleData->dataLen,
1617                                                            &midPacketCount,
1618                                                            &remainingLen,
1619                                                            &totalLength,
1620                                                            g_mtuSize);
1621
1622     if (CA_STATUS_OK != result)
1623     {
1624         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1625                   "CAGenerateVariableForFragmentation failed, result [%d]", result);
1626         if (g_errorHandler)
1627         {
1628             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1629         }
1630         return;
1631     }
1632
1633     OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
1634               "Packet info: data size[%d] midPacketCount[%u] remainingLen[%" PRIuPTR "] totalLength[%" PRIuPTR "]",
1635               bleData->dataLen, midPacketCount, remainingLen, totalLength);
1636
1637     uint8_t dataSegment[CA_SUPPORTED_BLE_MTU_SIZE] = {0};
1638     uint8_t dataHeader[CA_BLE_HEADER_SIZE] = {0};
1639
1640     if (NULL != bleData->remoteEndpoint) //Unicast Data
1641     {
1642         secureFlag = (bleData->remoteEndpoint->flags & CA_SECURE) ?
1643             CA_BLE_PACKET_SECURE : CA_BLE_PACKET_NON_SECURE;
1644
1645         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This Packet is secure? %d", secureFlag);
1646         result = CAGenerateHeader(dataHeader,
1647                                   CA_BLE_PACKET_START,
1648                                   g_localBLESourcePort,
1649                                   secureFlag,
1650                                   bleData->remoteEndpoint->port);
1651     }
1652     else                                //Multicast Data
1653     {
1654         result = CAGenerateHeader(dataHeader,
1655                                   CA_BLE_PACKET_START,
1656                                   g_localBLESourcePort,
1657                                   secureFlag,
1658                                   CA_BLE_MULTICAST_PORT);
1659     }
1660
1661     if (CA_STATUS_OK != result)
1662     {
1663         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1664                   "CAGenerateHeader failed, result [%d]", result);
1665         if (g_errorHandler)
1666         {
1667             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1668         }
1669         return;
1670     }
1671
1672     uint8_t lengthHeader[CA_BLE_LENGTH_HEADER_SIZE] = {0};
1673     result = CAGenerateHeaderPayloadLength(lengthHeader,
1674                                            CA_BLE_LENGTH_HEADER_SIZE,
1675                                            bleData->dataLen);
1676
1677     if (CA_STATUS_OK != result)
1678     {
1679         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1680                   "CAGenerateHeaderPayloadLength failed, result [%d]", result);
1681         if (g_errorHandler)
1682         {
1683             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1684         }
1685         return;
1686     }
1687
1688     uint32_t length = 0;
1689     uint32_t dataLen = 0;
1690     if (g_mtuSize > totalLength)
1691     {
1692         length = totalLength;
1693         dataLen = bleData->dataLen;
1694     }
1695     else
1696     {
1697         length = g_mtuSize;
1698         dataLen = g_mtuSize - CA_BLE_HEADER_SIZE - CA_BLE_LENGTH_HEADER_SIZE;
1699     }
1700
1701     result = CAMakeFirstDataSegment(dataSegment,
1702                                     bleData->data, dataLen,
1703                                     dataHeader, lengthHeader);
1704
1705     if (CA_STATUS_OK != result)
1706     {
1707         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1708                   "Making data segment failed, result [%d]", result);
1709         if (g_errorHandler)
1710         {
1711             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1712         }
1713         return;
1714     }
1715
1716     const uint32_t iter = midPacketCount;
1717     uint32_t index = 0;
1718     if (NULL != bleData->remoteEndpoint) //Sending Unicast Data
1719     {
1720         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Unicast Data");
1721         // Send the first segment with the header.
1722         result =
1723             CAUpdateCharacteristicsToGattServer(
1724                 bleData->remoteEndpoint->addr,
1725                 dataSegment,
1726                 length,
1727                 LE_UNICAST,
1728                 0);
1729
1730         if (CA_STATUS_OK != result)
1731         {
1732             OIC_LOG_V(ERROR,
1733                       CALEADAPTER_TAG,
1734                       "Update characteristics failed, result [%d]",
1735                       result);
1736             if (g_errorHandler)
1737             {
1738                 g_errorHandler(bleData->remoteEndpoint,
1739                                bleData->data,
1740                                bleData->dataLen,
1741                                result);
1742             }
1743             return;
1744         }
1745         OIC_LOG_V(DEBUG,
1746                   CALEADAPTER_TAG,
1747                   "Client Sent Unicast First Data - data length [%u]",
1748                   length);
1749
1750         result = CAGenerateHeader(dataHeader,
1751                                   CA_BLE_PACKET_NOT_START,
1752                                   g_localBLESourcePort,
1753                                   secureFlag,
1754                                   bleData->remoteEndpoint->port);
1755
1756         if (CA_STATUS_OK != result)
1757         {
1758             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1759                       "CAGenerateHeader failed, result [%d]", result);
1760             if (g_errorHandler)
1761             {
1762                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1763             }
1764             return;
1765         }
1766
1767         for (index = 0; index < iter; index++)
1768         {
1769             result = CAMakeRemainDataSegment(dataSegment,
1770                                              g_mtuSize - CA_BLE_HEADER_SIZE,
1771                                              bleData->data,
1772                                              bleData->dataLen,
1773                                              index,
1774                                              dataHeader,
1775                                              g_mtuSize);
1776
1777             if (CA_STATUS_OK != result)
1778             {
1779                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1780                             "Making data segment failed, result [%d]", result);
1781                 if (g_errorHandler)
1782                 {
1783                     g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1784                 }
1785                 return;
1786             }
1787
1788             // Send the remaining header.
1789             result = CAUpdateCharacteristicsToGattServer(
1790                      bleData->remoteEndpoint->addr,
1791                      dataSegment,
1792                      g_mtuSize,
1793                      LE_UNICAST, 0);
1794
1795             if (CA_STATUS_OK != result)
1796             {
1797                 OIC_LOG_V(ERROR,
1798                           CALEADAPTER_TAG,
1799                           "Update characteristics failed, result [%d]",
1800                           result);
1801                 if (g_errorHandler)
1802                 {
1803                     g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1804                 }
1805                 return;
1806             }
1807             OIC_LOG_V(DEBUG,
1808                       CALEADAPTER_TAG,
1809                       "Client Sent Unicast %d Data - data(mtu) length [%u]",
1810                       index + 1,
1811                       g_mtuSize);
1812         }
1813
1814         if (remainingLen && (totalLength > g_mtuSize))
1815         {
1816             // send the last segment of the data (Ex: 22 bytes of 622
1817             // bytes of data when MTU is 200)
1818             result = CAMakeRemainDataSegment(dataSegment,
1819                                              remainingLen,
1820                                              bleData->data,
1821                                              bleData->dataLen,
1822                                              index,
1823                                              dataHeader,
1824                                              g_mtuSize);
1825
1826             if (CA_STATUS_OK != result)
1827             {
1828                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1829                             "Making data segment failed, result [%d]", result);
1830                 if (g_errorHandler)
1831                 {
1832                     g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1833                 }
1834                 return;
1835             }
1836
1837             result = CAUpdateCharacteristicsToGattServer(
1838                      bleData->remoteEndpoint->addr,
1839                      dataSegment,
1840                      remainingLen + CA_BLE_HEADER_SIZE,
1841                      LE_UNICAST, 0);
1842
1843             if (CA_STATUS_OK != result)
1844             {
1845                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1846                                                    result);
1847                 if (g_errorHandler)
1848                 {
1849                     g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1850                 }
1851                 return;
1852             }
1853             OIC_LOG_V(DEBUG,
1854                       CALEADAPTER_TAG,
1855                       "Client Sent Unicast Last Data - data length [%" PRIuPTR "]",
1856                       remainingLen + CA_BLE_HEADER_SIZE);
1857         }
1858     }
1859     else
1860     {
1861 #if defined(__TIZEN__)
1862         // @todo
1863         // tizen ble should also disabled when Tizen 3.0 is updated.
1864         //Sending Mulitcast Data
1865         // Send the first segment with the header.
1866         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Client Sending Multicast Data");
1867         result = CAUpdateCharacteristicsToAllGattServers(dataSegment, length);
1868         if (CA_STATUS_OK != result)
1869         {
1870             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1871                       "Update characteristics (all) failed, result [%d]", result);
1872             CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1873             return;
1874         }
1875
1876         result = CAGenerateHeader(dataHeader,
1877                                   CA_BLE_PACKET_NOT_START,
1878                                   g_localBLESourcePort,
1879                                   secureFlag,
1880                                   0);
1881
1882         if (CA_STATUS_OK != result)
1883         {
1884             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1885                       "CAGenerateHeader failed, result [%d]", result);
1886             if (g_errorHandler)
1887             {
1888                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1889             }
1890             return;
1891         }
1892         OIC_LOG_V(DEBUG,
1893                   CALEADAPTER_TAG,
1894                   "Client Sent Multicast First Data - data length [%zu]",
1895                   length);
1896
1897         for (index = 0; index < iter; index++)
1898         {
1899             // Send the remaining header.
1900             result = CAMakeRemainDataSegment(dataSegment,
1901                                              CA_BLE_NORMAL_SEGMENT_PAYLOAD_SIZE,
1902                                              bleData->data,
1903                                              bleData->dataLen,
1904                                              index,
1905                                              dataHeader);
1906
1907             if (CA_STATUS_OK != result)
1908             {
1909                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1910                             "Making data segment failed, result [%d]", result);
1911                 if (g_errorHandler)
1912                 {
1913                     g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1914                 }
1915                 return;
1916             }
1917
1918             result = CAUpdateCharacteristicsToAllGattServers(
1919                          dataSegment,
1920                          CA_SUPPORTED_BLE_MTU_SIZE);
1921
1922             if (CA_STATUS_OK != result)
1923             {
1924                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1925                           result);
1926                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1927                 return;
1928             }
1929             OIC_LOG_V(DEBUG,
1930                       CALEADAPTER_TAG,
1931                       "Client Sent Multicast %d Data - data length [%zu]",
1932                       index + 1,
1933                       CA_SUPPORTED_BLE_MTU_SIZE);
1934         }
1935
1936         if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
1937         {
1938             // send the last segment of the data (Ex: 22 bytes of 622
1939             // bytes of data when MTU is 200)
1940             result = CAMakeRemainDataSegment(dataSegment,
1941                                              remainingLen,
1942                                              bleData->data,
1943                                              bleData->dataLen,
1944                                              index,
1945                                              dataHeader);
1946
1947             if (CA_STATUS_OK != result)
1948             {
1949                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1950                             "Making data segment failed, result [%d]", result);
1951                 if (g_errorHandler)
1952                 {
1953                     g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1954                 }
1955                 return;
1956             }
1957
1958             result =
1959                 CAUpdateCharacteristicsToAllGattServers(
1960                     dataSegment,
1961                     remainingLen + CA_BLE_HEADER_SIZE);
1962
1963             if (CA_STATUS_OK != result)
1964             {
1965                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1966                           "Update characteristics (all) failed, result [%d]", result);
1967                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1968                 return;
1969             }
1970             OIC_LOG_V(DEBUG,
1971                       CALEADAPTER_TAG,
1972                       "Client Sent Multicast Last Data - data length [%" PRIuPTR "]",
1973                       remainingLen + CA_BLE_HEADER_SIZE);
1974         }
1975 #else
1976         OIC_LOG(DEBUG, CALEADAPTER_TAG, "BLE Multicast is not supported");
1977     }
1978 #endif
1979     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CABLEClientSendDataThread");
1980 }
1981
1982 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
1983                                   const uint8_t *data,
1984                                   uint32_t dataLength,
1985                                   u_arraylist_t *senderInfo)
1986 {
1987     CALEData_t * const bleData = OICMalloc(sizeof(CALEData_t));
1988
1989     if (!bleData)
1990     {
1991         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1992         return NULL;
1993     }
1994
1995     bleData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
1996     bleData->data = OICCalloc(dataLength + 1, 1);
1997
1998     if (NULL == bleData->data)
1999     {
2000         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
2001         CAFreeLEData(bleData);
2002         return NULL;
2003     }
2004
2005     memcpy(bleData->data, data, dataLength);
2006     bleData->dataLen = dataLength;
2007     if (senderInfo)
2008     {
2009         bleData->senderInfo = senderInfo;
2010     }
2011
2012     return bleData;
2013 }
2014
2015 static void CAFreeLEData(CALEData_t *bleData)
2016 {
2017     VERIFY_NON_NULL_VOID(bleData, CALEADAPTER_TAG, "Param bleData is NULL");
2018
2019     CAFreeEndpoint(bleData->remoteEndpoint);
2020     OICFree(bleData->data);
2021     OICFree(bleData);
2022 }
2023
2024 static void CALEDataDestroyer(void *data, uint32_t size)
2025 {
2026     if ((size_t)size < sizeof(CALEData_t *))
2027     {
2028         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2029                   "Destroy data too small %p %d", data, size);
2030     }
2031     CALEData_t *ledata = (CALEData_t *) data;
2032
2033     CAFreeLEData(ledata);
2034 }
2035
2036
2037 static CAResult_t CAInitLEAdapterMutex()
2038 {
2039     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAInitLEAdapterMutex");
2040
2041     if (NULL == g_bleIsServerMutex)
2042     {
2043         g_bleIsServerMutex = oc_mutex_new();
2044         if (NULL == g_bleIsServerMutex)
2045         {
2046             OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2047             return CA_STATUS_FAILED;
2048         }
2049     }
2050
2051     if (NULL == g_bleNetworkCbMutex)
2052     {
2053         g_bleNetworkCbMutex = oc_mutex_new();
2054         if (NULL == g_bleNetworkCbMutex)
2055         {
2056             OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2057             CATerminateLEAdapterMutex();
2058             return CA_STATUS_FAILED;
2059         }
2060     }
2061
2062     if (NULL == g_bleLocalAddressMutex)
2063     {
2064         g_bleLocalAddressMutex = oc_mutex_new();
2065         if (NULL == g_bleLocalAddressMutex)
2066         {
2067             OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2068             CATerminateLEAdapterMutex();
2069             return CA_STATUS_FAILED;
2070         }
2071     }
2072
2073     if (NULL == g_bleAdapterThreadPoolMutex)
2074     {
2075         g_bleAdapterThreadPoolMutex = oc_mutex_new();
2076         if (NULL == g_bleAdapterThreadPoolMutex)
2077         {
2078             OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2079             CATerminateLEAdapterMutex();
2080             return CA_STATUS_FAILED;
2081         }
2082     }
2083
2084     if (NULL == g_bleClientSendDataMutex)
2085     {
2086         g_bleClientSendDataMutex = oc_mutex_new();
2087         if (NULL == g_bleClientSendDataMutex)
2088         {
2089             OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2090             CATerminateLEAdapterMutex();
2091             return CA_STATUS_FAILED;
2092         }
2093     }
2094
2095     if (NULL == g_bleServerSendDataMutex)
2096     {
2097         g_bleServerSendDataMutex = oc_mutex_new();
2098         if (NULL == g_bleServerSendDataMutex)
2099         {
2100             OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2101             CATerminateLEAdapterMutex();
2102             return CA_STATUS_FAILED;
2103         }
2104     }
2105
2106     if (NULL == g_bleAdapterReqRespCbMutex)
2107     {
2108         g_bleAdapterReqRespCbMutex = oc_mutex_new();
2109         if (NULL == g_bleAdapterReqRespCbMutex)
2110         {
2111             OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2112             CATerminateLEAdapterMutex();
2113             return CA_STATUS_FAILED;
2114         }
2115     }
2116
2117     if (NULL == g_bleServerReceiveDataMutex)
2118     {
2119         g_bleServerReceiveDataMutex = oc_mutex_new();
2120         if (NULL == g_bleServerReceiveDataMutex)
2121         {
2122             OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2123             return CA_STATUS_FAILED;
2124         }
2125     }
2126
2127     if (NULL == g_bleClientReceiveDataMutex)
2128     {
2129         g_bleClientReceiveDataMutex = oc_mutex_new();
2130         if (NULL == g_bleClientReceiveDataMutex)
2131         {
2132             OIC_LOG(ERROR, CALEADAPTER_TAG, "oc_mutex_new failed");
2133             return CA_STATUS_FAILED;
2134         }
2135     }
2136
2137     return CA_STATUS_OK;
2138 }
2139
2140 static void CATerminateLEAdapterMutex()
2141 {
2142     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CATerminateLEAdapterMutex");
2143
2144     oc_mutex_free(g_bleIsServerMutex);
2145     g_bleIsServerMutex = NULL;
2146
2147     oc_mutex_free(g_bleNetworkCbMutex);
2148     g_bleNetworkCbMutex = NULL;
2149
2150     oc_mutex_free(g_bleLocalAddressMutex);
2151     g_bleLocalAddressMutex = NULL;
2152
2153     oc_mutex_free(g_bleAdapterThreadPoolMutex);
2154     g_bleAdapterThreadPoolMutex = NULL;
2155
2156     oc_mutex_free(g_bleClientSendDataMutex);
2157     g_bleClientSendDataMutex = NULL;
2158
2159     oc_mutex_free(g_bleServerSendDataMutex);
2160     g_bleServerSendDataMutex = NULL;
2161
2162     oc_mutex_free(g_bleAdapterReqRespCbMutex);
2163     g_bleAdapterReqRespCbMutex = NULL;
2164
2165     oc_mutex_free(g_bleServerReceiveDataMutex);
2166     g_bleServerReceiveDataMutex = NULL;
2167
2168     oc_mutex_free(g_bleClientReceiveDataMutex);
2169     g_bleClientReceiveDataMutex = NULL;
2170 }
2171
2172 /**
2173  * Starting LE connectivity adapters.
2174  *
2175  * As its peer to peer it does not require to start any servers.
2176  *
2177  * @return ::CA_STATUS_OK or Appropriate error code.
2178  */
2179 static CAResult_t CAStartLE();
2180
2181 /**
2182  * Start listening server for receiving multicast search requests.
2183  *
2184  * Transport Specific Behavior:
2185  *   LE  Starts GATT Server with prefixed UUID and Characteristics
2186  *   per OIC Specification.
2187  * @return  ::CA_STATUS_OK or Appropriate error code.
2188  */
2189 static CAResult_t CAStartLEListeningServer();
2190
2191 /**
2192  * Stops listening server from receiving multicast search requests.
2193  *
2194  * Transport Specific Behavior:
2195  *   LE  Starts GATT Server with prefixed UUID and Characteristics
2196  *   per OIC Specification.
2197  * @return  ::CA_STATUS_OK or Appropriate error code.
2198  */
2199 static CAResult_t CAStopLEListeningServer();
2200
2201 /**
2202  * Sarting discovery of servers for receiving multicast
2203  * advertisements.
2204  *
2205  * Transport Specific Behavior:
2206  *   LE  Starts GATT Server with prefixed UUID and Characteristics
2207  *   per OIC Specification.
2208  *
2209  * @return ::CA_STATUS_OK or Appropriate error code
2210  */
2211 static CAResult_t CAStartLEDiscoveryServer();
2212
2213 /**
2214  * Send data to the endpoint using the adapter connectivity.
2215  *
2216  * @param[in] endpoint Remote Endpoint information (like MAC address,
2217  *                     reference URI and connectivity type) to which
2218  *                     the unicast data has to be sent.
2219  * @param[in] data     Data which required to be sent.
2220  * @param[in] dataLen  Size of data to be sent.
2221  *
2222  * @note  dataLen must be > 0.
2223  *
2224  * @return The number of bytes sent on the network, or -1 on error.
2225  */
2226 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
2227                                    const void *data,
2228                                    uint32_t dataLen,
2229                                    CADataType_t dataType);
2230
2231 /**
2232  * Send multicast data to the endpoint using the LE connectivity.
2233  *
2234  * @param[in] endpoint Remote Endpoint information to which the
2235  *                     multicast data has to be sent.
2236  * @param[in] data     Data which required to be sent.
2237  * @param[in] dataLen  Size of data to be sent.
2238  *
2239  * @note  dataLen must be > 0.
2240  *
2241  * @return The number of bytes sent on the network, or -1 on error.
2242  */
2243 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
2244                                      const void *data,
2245                                      uint32_t dataLen,
2246                                      CADataType_t dataType);
2247
2248 /**
2249  * Get LE Connectivity network information.
2250  *
2251  * @param[out] info Local connectivity information structures.
2252  * @param[out] size Number of local connectivity structures.
2253  *
2254  * @return ::CA_STATUS_OK or Appropriate error code.
2255  */
2256 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info,
2257                                               size_t *size);
2258
2259 /**
2260  * Read Synchronous API callback.
2261  *
2262  * @return  ::CA_STATUS_OK or Appropriate error code.
2263  */
2264 static CAResult_t CAReadLEData();
2265
2266 /**
2267  * Stopping the adapters and close socket connections.
2268  *
2269  * LE Stops all GATT servers and GATT Clients.
2270  *
2271  * @return ::CA_STATUS_OK or Appropriate error code.
2272  */
2273 static CAResult_t CAStopLE();
2274
2275 /**
2276  * Terminate the LE connectivity adapter.
2277  *
2278  * Configuration information will be deleted from further use.
2279  */
2280 static void CATerminateLE();
2281
2282 /**
2283  * This function will receive the data from the GattServer and add the
2284  * data to the Server receiver queue.
2285  *
2286  * @param[in] remoteAddress Remote address of the device from where
2287  *                          data is received.
2288  * @param[in] data          Actual data received from the remote
2289  *                          device.
2290  * @param[in] dataLength    Length of the data received from the
2291  *                          remote device.
2292  * @param[in] sentLength    Length of the data sent from the remote
2293  *                          device.
2294  *
2295  * @return ::CA_STATUS_OK or Appropriate error code.
2296  * @retval ::CA_STATUS_OK  Successful.
2297  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
2298  * @retval ::CA_STATUS_FAILED Operation failed.
2299  *
2300  */
2301 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
2302                                                 const uint8_t *data,
2303                                                 uint32_t dataLength,
2304                                                 uint32_t *sentLength);
2305
2306 /**
2307  * This function will receive the data from the GattClient and add the
2308  * data into the Client receiver queue.
2309  *
2310  * @param[in] remoteAddress Remote address of the device from where
2311  *                          data is received.
2312  * @param[in] data          Actual data recevied from the remote
2313  *                          device.
2314  * @param[in] dataLength    Length of the data received from the
2315  *                          remote device.
2316  * @param[in] sentLength    Length of the data sent from the remote
2317  *                          device.
2318  *
2319  * @return ::CA_STATUS_OK or Appropriate error code.
2320  * @retval ::CA_STATUS_OK  Successful.
2321  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
2322  * @retval ::CA_STATUS_FAILED Operation failed.
2323  */
2324 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
2325                                                 const uint8_t *data,
2326                                                 uint32_t dataLength,
2327                                                 uint32_t *sentLength);
2328
2329 /**
2330  * Set the NetworkPacket received callback to CA layer from adapter
2331  * layer.
2332  *
2333  * @param[in] callback Callback handle sent from the upper layer.
2334  */
2335 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback);
2336
2337 /**
2338  * Push the data from CA layer to the Sender processor queue.
2339  *
2340  * @param[in] remoteEndpoint Remote endpoint information of the
2341  *                           server.
2342  * @param[in] data           Data to be transmitted from LE.
2343  * @param[in] dataLen        Length of the Data being transmitted.
2344  *
2345  * @return ::CA_STATUS_OK or Appropriate error code.
2346  * @retval ::CA_STATUS_OK  Successful.
2347  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
2348  * @retval ::CA_STATUS_FAILED Operation failed.
2349  */
2350 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
2351                                             const uint8_t *data,
2352                                             uint32_t dataLen);
2353
2354 /**
2355  * Push the data from CA layer to the Sender processor queue.
2356  *
2357  * @param[in] remoteEndpoint Remote endpoint information of the
2358  *                           server.
2359  * @param[in] data           Data to be transmitted from LE.
2360  * @param[in] dataLen        Length of the Data being transmitted.
2361  *
2362  * @return ::CA_STATUS_OK or Appropriate error code.
2363  * @retval ::CA_STATUS_OK  Successful.
2364  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
2365  * @retval ::CA_STATUS_FAILED Operation failed.
2366  */
2367 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
2368                                             const uint8_t *data,
2369                                             uint32_t dataLen);
2370
2371 static CAResult_t CALEAdapterGattServerStart()
2372 {
2373     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEAdapterGattServerStart");
2374
2375     if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2376     {
2377         OIC_LOG_V(INFO, CALEADAPTER_TAG, "server's flag is disabled in configuration [%d]",
2378                   caglobals.bleFlags);
2379         return CA_STATUS_OK;
2380     }
2381
2382     CAResult_t result = CAStartLEGattServer();
2383
2384     /*
2385       Don't start the server side sending queue thread until the
2386       server itself has actually started.
2387     */
2388     if (CA_STATUS_OK == result)
2389     {
2390         oc_mutex_lock(g_bleServerSendDataMutex);
2391         result = CAQueueingThreadStart(g_bleServerSendQueueHandle);
2392         oc_mutex_unlock(g_bleServerSendDataMutex);
2393
2394         if (CA_STATUS_OK != result)
2395         {
2396             OIC_LOG_V(ERROR,
2397                       CALEADAPTER_TAG,
2398                       "Unable to start server queuing thread (%d)",
2399                       result);
2400         }
2401     }
2402
2403     return result;
2404 }
2405
2406 static CAResult_t CALEAdapterGattServerStop()
2407 {
2408     OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Stop");
2409
2410     if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2411     {
2412         OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2413                   caglobals.bleFlags);
2414         return CA_STATUS_OK;
2415     }
2416
2417
2418     CAResult_t res = CAStopLEGattServer();
2419     if (CA_STATUS_OK != res)
2420     {
2421         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAStopLEGattServer has failed");
2422     }
2423
2424     oc_mutex_lock(g_bleServerSendDataMutex);
2425     res = CAQueueingThreadStop(g_bleServerSendQueueHandle);
2426     if (CA_STATUS_OK != res)
2427     {
2428         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAQueueingThreadStop has failed");
2429     }
2430     oc_mutex_unlock(g_bleServerSendDataMutex);
2431
2432     return res;
2433 }
2434
2435 static CAResult_t CALEAdapterGattClientStart()
2436 {
2437     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEAdapterGattClientStart");
2438
2439     CAResult_t result = CAStartLEGattClient();
2440
2441     /*
2442       Don't start the client side sending queue thread until the
2443       client itself has actually started.
2444     */
2445     if (CA_STATUS_OK == result)
2446     {
2447         oc_mutex_lock(g_bleClientSendDataMutex);
2448         result = CAQueueingThreadStart(g_bleClientSendQueueHandle);
2449         oc_mutex_unlock(g_bleClientSendDataMutex);
2450
2451         if (CA_STATUS_OK != result)
2452         {
2453             OIC_LOG(ERROR,
2454                     CALEADAPTER_TAG,
2455                     "Unable to start client queuing thread");
2456         }
2457     }
2458
2459     return result;
2460 }
2461
2462 static CAResult_t CALEAdapterGattClientStop()
2463 {
2464     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEAdapterGattClientStop");
2465     CAStopLEGattClient();
2466
2467     oc_mutex_lock(g_bleClientSendDataMutex);
2468     CAResult_t result = CAQueueingThreadStop(g_bleClientSendQueueHandle);
2469     oc_mutex_unlock(g_bleClientSendDataMutex);
2470
2471     return result;
2472 }
2473
2474 #ifdef __WITH_DTLS__
2475 static ssize_t CALESecureSendDataCB(CAEndpoint_t *endpoint,
2476                              const void *data, size_t dataLen)
2477 {
2478     VERIFY_NON_NULL_RET(endpoint, CALEADAPTER_TAG, "endpoint is NULL", -1);
2479     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "data is NULL", -1);
2480
2481     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Secure Data Send - encrypted datalen = %" PRIuPTR, dataLen);
2482
2483     CAResult_t result;
2484     CADataType_t dataType = g_dataType;
2485
2486     if (ADAPTER_SERVER == g_adapterType ||
2487             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2488     {
2489         result = CALEAdapterServerSendData(endpoint, data, dataLen);
2490         if (CA_STATUS_OK != result)
2491         {
2492             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed" );
2493
2494             if (g_errorHandler)
2495             {
2496                 g_errorHandler(endpoint, data, dataLen, result);
2497             }
2498             return -1;
2499         }
2500     }
2501     else if (ADAPTER_CLIENT == g_adapterType ||
2502             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
2503             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
2504     {
2505         result = CALEAdapterClientSendData(endpoint, data, dataLen);
2506         if (CA_STATUS_OK != result)
2507         {
2508             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for client failed" );
2509
2510             if (g_errorHandler)
2511             {
2512                 g_errorHandler(endpoint, data, dataLen, result);
2513             }
2514             return -1;
2515         }
2516     }
2517     else
2518     {
2519         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
2520                   "Can't Send Message adapterType = %d, dataType = %d", g_adapterType, dataType);
2521         return -1;
2522     }
2523
2524     return (ssize_t)dataLen;
2525 }
2526
2527 static void CALESecureReceiveDataCB(const CASecureEndpoint_t *sep,
2528                                  const void *data, size_t dataLen)
2529 {
2530     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2531
2532     VERIFY_NON_NULL_VOID(sep, CALEADAPTER_TAG, "sep is NULL");
2533     VERIFY_NON_NULL_VOID(data, CALEADAPTER_TAG, "data is NULL");
2534
2535     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Secure Data Receive - decrypted datalen = %" PRIuPTR, dataLen);
2536
2537     if (dataLen == 0)
2538     {
2539         OIC_LOG(ERROR, CALEADAPTER_TAG, "incorrect dataLen, derecypt fail !");
2540         return;
2541     }
2542
2543     OIC_LOG_BUFFER(DEBUG, CALEADAPTER_TAG, data, dataLen);
2544
2545     if (g_networkPacketReceivedCallback)
2546     {
2547         OIC_LOG_V(DEBUG, CALEADAPTER_TAG,
2548                   "[CALESecureReceiveDataCB] Secure flags = %d, %x",
2549                   sep->endpoint.flags, sep->endpoint.flags);
2550         OIC_LOG(DEBUG, CALEADAPTER_TAG,
2551                   "[CALESecureReceiveDataCB] Received data up !");
2552         g_networkPacketReceivedCallback(sep, data, dataLen);
2553     }
2554 }
2555 #endif
2556
2557 static void CALEErrorHandlerInternal(const CAEndpoint_t *endpoint,
2558                                      const void *data, size_t dataLen,
2559                                      CAResult_t result)
2560 {
2561     g_errorHandler(endpoint, data, dataLen, result);
2562 }
2563
2564 CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
2565                           CANetworkPacketReceivedCallback reqRespCallback,
2566                           CAAdapterChangeCallback netCallback,
2567                           CAConnectionChangeCallback connCallback,
2568                           CAErrorHandleCallback errorCallback,
2569                           ca_thread_pool_t handle)
2570 {
2571     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAInitializeLE");
2572
2573     //Input validation
2574     VERIFY_NON_NULL(registerCallback, CALEADAPTER_TAG, "RegisterConnectivity callback is null");
2575     VERIFY_NON_NULL(reqRespCallback, CALEADAPTER_TAG, "PacketReceived Callback is null");
2576     VERIFY_NON_NULL(netCallback, CALEADAPTER_TAG, "NetworkChange Callback is null");
2577     VERIFY_NON_NULL(connCallback, CALEADAPTER_TAG, "ConnectionChange Callback is null");
2578
2579     CAResult_t result = CA_STATUS_OK;
2580     result = CAInitLEAdapterMutex();
2581     if (CA_STATUS_OK != result)
2582     {
2583         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleAdapterMutex failed!");
2584         return CA_STATUS_FAILED;
2585     }
2586
2587     result = CAInitializeLENetworkMonitor();
2588     if (CA_STATUS_OK != result)
2589     {
2590         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() failed");
2591         return CA_STATUS_FAILED;
2592     }
2593     CAInitializeLEAdapter();
2594
2595     result = CAInitializeLEGattClient();
2596     if (CA_STATUS_OK != result)
2597     {
2598         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattClient() failed");
2599         return CA_STATUS_FAILED;
2600     }
2601
2602     CASetLEClientThreadPoolHandle(handle);
2603
2604     CASetLEReqRespClientCallback(CALEAdapterClientReceivedData);
2605     CASetLEServerThreadPoolHandle(handle);
2606     result = CAInitializeLEGattServer();
2607     if (CA_STATUS_OK != result)
2608     {
2609         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattServer() failed");
2610         return CA_STATUS_FAILED;
2611     }
2612
2613     CASetLEAdapterThreadPoolHandle(handle);
2614     CASetLEReqRespServerCallback(CALEAdapterServerReceivedData);
2615     CASetLEReqRespAdapterCallback(reqRespCallback);
2616
2617     CASetBLEClientErrorHandleCallback(CALEErrorHandler);
2618     CASetBLEServerErrorHandleCallback(CALEErrorHandler);
2619     CALERegisterNetworkNotifications(netCallback, connCallback);
2620
2621     g_errorHandler = errorCallback;
2622
2623 #ifdef __WITH_DTLS__
2624      if (CA_STATUS_OK != CAinitSslAdapter())
2625     {
2626         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to init SSL adapter");
2627     }
2628     else
2629     {
2630         CAsetSslAdapterCallbacks(CALESecureReceiveDataCB, CALESecureSendDataCB, CALEErrorHandlerInternal, CA_ADAPTER_GATT_BTLE);
2631     }
2632 #endif
2633
2634     static const CAConnectivityHandler_t connHandler =
2635         {
2636             .startAdapter = CAStartLE,
2637             .stopAdapter = CAStopLE,
2638             .startListenServer = CAStartLEListeningServer,
2639             .stopListenServer = CAStopLEListeningServer,
2640             .startDiscoveryServer = CAStartLEDiscoveryServer,
2641             .sendData = CASendLEUnicastData,
2642             .sendDataToAll = CASendLEMulticastData,
2643             .GetnetInfo = CAGetLEInterfaceInformation,
2644             .readData = CAReadLEData,
2645             .terminate = CATerminateLE,
2646             .cType = CA_ADAPTER_GATT_BTLE
2647         };
2648
2649     registerCallback(connHandler);
2650     return CA_STATUS_OK;
2651 }
2652
2653 static CAResult_t CAStartLE()
2654 {
2655     return CAStartLEAdapter();
2656 }
2657
2658 static CAResult_t CAStopLE()
2659 {
2660 #ifdef __WITH_DTLS__
2661     CAdeinitSslAdapter();
2662 #endif
2663
2664     CAStopLEQueues();
2665
2666     oc_mutex_lock(g_bleIsServerMutex);
2667     switch (g_adapterType)
2668     {
2669         case ADAPTER_SERVER:
2670             CALEAdapterGattServerStop();
2671             break;
2672         case ADAPTER_CLIENT:
2673             CALEAdapterGattClientStop();
2674             break;
2675         case ADAPTER_BOTH_CLIENT_SERVER:
2676             CALEAdapterGattServerStop();
2677             CALEAdapterGattClientStop();
2678             break;
2679         default:
2680             break;
2681     }
2682     oc_mutex_unlock(g_bleIsServerMutex);
2683     return CAStopLEAdapter();
2684 }
2685
2686 static void CATerminateLE()
2687 {
2688     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CATerminateLE");
2689
2690     CASetLEReqRespServerCallback(NULL);
2691     CASetLEReqRespClientCallback(NULL);
2692     CALERegisterNetworkNotifications(NULL, NULL);
2693     CASetLEReqRespAdapterCallback(NULL);
2694     CATerminateLENetworkMonitor();
2695
2696     oc_mutex_lock(g_bleIsServerMutex);
2697     switch (g_adapterType)
2698     {
2699         case ADAPTER_SERVER:
2700             CATerminateLEGattServer();
2701             break;
2702         case ADAPTER_CLIENT:
2703             CATerminateLEGattClient();
2704             break;
2705         case ADAPTER_BOTH_CLIENT_SERVER:
2706             CATerminateLEGattServer();
2707             CATerminateLEGattClient();
2708             break;
2709         default:
2710             break;
2711     }
2712     g_adapterType = ADAPTER_EMPTY;
2713     oc_mutex_unlock(g_bleIsServerMutex);
2714
2715     CATerminateLEQueues();
2716
2717 #ifdef __WITH_DTLS__
2718     CAsetSslAdapterCallbacks(NULL, NULL, NULL, CA_ADAPTER_GATT_BTLE);
2719 #endif
2720
2721     CATerminateLEAdapterMutex();
2722 }
2723
2724 static CAResult_t CAStartLEListeningServer()
2725 {
2726     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAStartLEListeningServer");
2727
2728     if (caglobals.bleFlags & CA_LE_SERVER_DISABLE)
2729     {
2730         OIC_LOG_V(INFO, CALEADAPTER_TAG, "server flag of configure is disable [%d]",
2731                   caglobals.bleFlags);
2732         return CA_STATUS_OK;
2733     }
2734
2735 #ifndef ROUTING_GATEWAY
2736     CAResult_t result = CA_STATUS_OK;
2737     result = CAInitLEServerQueues();
2738     if (CA_STATUS_OK != result)
2739     {
2740         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerQueues failed");
2741         return result;
2742     }
2743
2744     oc_mutex_lock(g_bleIsServerMutex);
2745     switch (g_adapterType)
2746     {
2747         case ADAPTER_CLIENT:
2748             g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
2749             break;
2750         case ADAPTER_BOTH_CLIENT_SERVER:
2751             break;
2752         default:
2753             g_adapterType = ADAPTER_SERVER;
2754     }
2755     oc_mutex_unlock(g_bleIsServerMutex);
2756
2757     result = CAGetLEAdapterState();
2758     if (CA_STATUS_OK != result)
2759     {
2760         if (CA_ADAPTER_NOT_ENABLED == result)
2761         {
2762             OIC_LOG(DEBUG,
2763                     CALEADAPTER_TAG,
2764                     "Listen Server will be started once BT Adapter is enabled");
2765             result = CA_STATUS_OK;
2766         }
2767     }
2768     else
2769     {
2770         result = CALEAdapterGattServerStart();
2771     }
2772
2773     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2774     return result;
2775 #else // not ROUTING_GATEWAY
2776     // Routing Gateway only supports BLE client mode.
2777     OIC_LOG(ERROR, CALEADAPTER_TAG, "LE server not supported in Routing Gateway");
2778     return CA_NOT_SUPPORTED;
2779 #endif // not ROUTING_GATEWAY
2780 }
2781
2782 static CAResult_t CAStopLEListeningServer()
2783 {
2784     OIC_LOG(ERROR, CALEADAPTER_TAG, "Listen server stop not supported.");
2785     return CA_NOT_SUPPORTED;
2786 }
2787
2788 static CAResult_t CAStartLEDiscoveryServer()
2789 {
2790     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAStartLEDiscoveryServer");
2791     CAResult_t result = CA_STATUS_OK;
2792     result = CAInitLEClientQueues();
2793     if (CA_STATUS_OK != result)
2794     {
2795         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientQueues failed");
2796         return result;
2797     }
2798
2799     oc_mutex_lock(g_bleIsServerMutex);
2800     switch (g_adapterType)
2801     {
2802         case ADAPTER_SERVER:
2803             g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
2804             break;
2805         case ADAPTER_BOTH_CLIENT_SERVER:
2806             break;
2807         default:
2808             g_adapterType = ADAPTER_CLIENT;
2809     }
2810     oc_mutex_unlock(g_bleIsServerMutex);
2811
2812     result = CAGetLEAdapterState();
2813     if (CA_STATUS_OK != result)
2814     {
2815         if (CA_ADAPTER_NOT_ENABLED == result)
2816         {
2817             OIC_LOG(DEBUG,
2818                     CALEADAPTER_TAG,
2819                     "Discovery Server will be started once BT Adapter is enabled");
2820             result = CA_STATUS_OK;
2821         }
2822     }
2823     else
2824     {
2825         result = CALEAdapterGattClientStart();
2826     }
2827
2828     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2829     return result;
2830 }
2831
2832 static CAResult_t CAReadLEData()
2833 {
2834     return CA_STATUS_OK;
2835 }
2836
2837 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
2838                                    const void *data,
2839                                    uint32_t dataLen,
2840                                    CADataType_t dataType)
2841 {
2842     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN - CASendLEUnicastData : type(%d)", dataType);
2843
2844     //Input validation
2845     VERIFY_NON_NULL_RET(endpoint, CALEADAPTER_TAG, "Remote endpoint is null", -1);
2846     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
2847
2848     CAResult_t result = CA_STATUS_FAILED;
2849
2850     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
2851     if (ADAPTER_EMPTY == g_adapterType)
2852     {
2853         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
2854     }
2855
2856     oc_mutex_lock(g_bleIsServerMutex);
2857     if (ADAPTER_SERVER == g_adapterType ||
2858             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2859     {
2860 #ifdef __WITH_DTLS__
2861         if (endpoint && endpoint->flags & CA_SECURE)
2862         {
2863             OIC_LOG(DEBUG, CALEADAPTER_TAG,
2864                     "Response Data or server - secured data send(caadapternetdtlsencrypt) call");
2865             g_dataType = dataType;
2866             oc_mutex_unlock(g_bleIsServerMutex);
2867
2868             result = CAencryptSsl(endpoint, data, dataLen);
2869             if (CA_STATUS_OK != result)
2870             {
2871                 OIC_LOG(ERROR, CALEADAPTER_TAG, "caadapternetdtlsencrypt failed!");
2872                 return -1;
2873             }
2874             return dataLen;
2875         }
2876         else
2877         {
2878             OIC_LOG(DEBUG, CALEADAPTER_TAG,
2879                     "server or both - none secured data send(CALEAdapterServerSendData) call");
2880             result = CALEAdapterServerSendData(endpoint, data, dataLen);
2881         }
2882 #else
2883         result = CALEAdapterServerSendData(endpoint, data, dataLen);
2884 #endif
2885         if (CA_STATUS_OK != result)
2886         {
2887             oc_mutex_unlock(g_bleIsServerMutex);
2888             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed");
2889             if (g_errorHandler)
2890             {
2891                 g_errorHandler(endpoint, data, dataLen, result);
2892             }
2893
2894             return -1;
2895         }
2896     }
2897     else if (ADAPTER_CLIENT == g_adapterType ||
2898             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
2899             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
2900     {
2901 #ifdef __WITH_DTLS__
2902         if (endpoint && endpoint->flags & CA_SECURE)
2903         {
2904             OIC_LOG(DEBUG, CALEADAPTER_TAG,
2905                     "Request Data or client - secured data send(caadapternetdtlsencrypt) call");
2906             g_dataType = dataType;
2907             oc_mutex_unlock(g_bleIsServerMutex);
2908
2909             result = CAencryptSsl(endpoint, data, dataLen);
2910             if (CA_STATUS_OK != result)
2911             {
2912                 OIC_LOG(ERROR, CALEADAPTER_TAG, "caadapternetdtlsencrypt failed!");
2913                 return -1;
2914             }
2915             return dataLen;
2916         }
2917         else
2918         {
2919             OIC_LOG(DEBUG, CALEADAPTER_TAG,
2920                     "client or both - none secured data send(CALEAdapterClientSendData) call");
2921             result = CALEAdapterClientSendData(endpoint, data, dataLen);
2922         }
2923 #else
2924         result = CALEAdapterClientSendData(endpoint, data, dataLen);
2925 #endif
2926         if (CA_STATUS_OK != result)
2927         {
2928             oc_mutex_unlock(g_bleIsServerMutex);
2929             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for client failed" );
2930
2931             if (g_errorHandler)
2932             {
2933                 g_errorHandler(endpoint, data, dataLen, result);
2934             }
2935             return -1;
2936         }
2937     }
2938     oc_mutex_unlock(g_bleIsServerMutex);
2939
2940     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2941     return dataLen;
2942 }
2943
2944 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
2945                                      const void *data,
2946                                      uint32_t dataLen,
2947                                      CADataType_t dataType)
2948 {
2949     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CASendLEMulticastData");
2950
2951     //Input validation
2952     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
2953
2954     if (0 >= dataLen)
2955     {
2956         OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
2957         return -1;
2958     }
2959
2960     CAResult_t result = CA_STATUS_FAILED;
2961
2962     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
2963     if (ADAPTER_EMPTY == g_adapterType)
2964     {
2965         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
2966     }
2967
2968     oc_mutex_lock(g_bleIsServerMutex);
2969     if (ADAPTER_SERVER == g_adapterType ||
2970             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_DATA == dataType))
2971     {
2972         result = CALEAdapterServerSendData(NULL, data, dataLen);
2973         if (CA_STATUS_OK != result)
2974         {
2975             oc_mutex_unlock(g_bleIsServerMutex);
2976
2977             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send multicast data for server failed" );
2978
2979             if (g_errorHandler)
2980             {
2981                 g_errorHandler(endpoint, data, dataLen, result);
2982             }
2983             return -1;
2984         }
2985     }
2986
2987     if (ADAPTER_CLIENT == g_adapterType ||
2988             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_REQUEST_DATA == dataType) ||
2989             (ADAPTER_BOTH_CLIENT_SERVER == g_adapterType && CA_RESPONSE_FOR_RES == dataType))
2990     {
2991         result = CALEAdapterClientSendData(NULL, data, dataLen);
2992         if (CA_STATUS_OK != result)
2993         {
2994             oc_mutex_unlock(g_bleIsServerMutex);
2995
2996             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send Multicast data for client failed" );
2997
2998             if (g_errorHandler)
2999             {
3000                 g_errorHandler(endpoint, data, dataLen, result);
3001             }
3002             return -1;
3003         }
3004     }
3005     oc_mutex_unlock(g_bleIsServerMutex);
3006
3007     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CASendLEMulticastData");
3008     return dataLen;
3009 }
3010
3011 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, size_t *size)
3012 {
3013     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
3014
3015     VERIFY_NON_NULL(info, CALEADAPTER_TAG, "CALocalConnectivity info is null");
3016
3017     char *local_address = NULL;
3018
3019     CAResult_t res = CAGetLEAddress(&local_address);
3020     if (CA_STATUS_OK != res)
3021     {
3022         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAGetLEAddress has failed");
3023         return res;
3024     }
3025
3026     if (NULL == local_address)
3027     {
3028         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is NULL");
3029         return CA_STATUS_FAILED;
3030     }
3031
3032     *size = 0;
3033     (*info) = (CAEndpoint_t *) OICCalloc(1, sizeof(CAEndpoint_t));
3034     if (NULL == (*info))