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