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