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