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