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