Update snapshot(2017-12-06)
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / tcp_adapter / catcpadapter.c
1 /* ****************************************************************
2  *
3  * Copyright 2015 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
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <stdint.h>
25
26 #ifndef __STDC_FORMAT_MACROS
27 #define __STDC_FORMAT_MACROS
28 #endif
29 #include <inttypes.h>
30
31 #include "cainterface.h"
32 #include "caipnwmonitor.h"
33 #include "catcpadapter.h"
34 #include "catcpinterface.h"
35 #include "caqueueingthread.h"
36 #include "caadapterutils.h"
37 #include "octhread.h"
38 #include "uarraylist.h"
39 #include "caremotehandler.h"
40 #include "logger.h"
41 #include "oic_malloc.h"
42 #ifdef __WITH_TLS__
43 #include "ca_adapter_net_ssl.h"
44 #endif
45
46 /**
47  * Logging tag for module name.
48  */
49 #define TAG "OIC_CA_TCP_ADAP"
50
51 /**
52  * Holds internal thread TCP data information.
53  */
54 typedef struct
55 {
56     CAEndpoint_t *remoteEndpoint;
57     void *data;
58     size_t dataLen;
59     bool isMulticast;
60 } CATCPData;
61
62 #define CA_TCP_LISTEN_BACKLOG  3
63
64 #define CA_TCP_SELECT_TIMEOUT 10
65
66 /**
67  * Queue handle for Send Data.
68  */
69 static CAQueueingThread_t *g_sendQueueHandle = NULL;
70
71 /**
72  * Network Packet Received Callback to CA.
73  */
74 static CANetworkPacketReceivedCallback g_networkPacketCallback = NULL;
75
76 /**
77  * Adapter Changed Callback to CA.
78  */
79 static CAAdapterChangeCallback g_networkChangeCallback = NULL;
80
81 /**
82  * Connection Changed Callback to CA.
83  */
84 static CAConnectionChangeCallback g_connectionChangeCallback = NULL;
85
86 /**
87  * error Callback to CA adapter.
88  */
89 static CAErrorHandleCallback g_errorCallback = NULL;
90
91 /**
92  * KeepAlive Connected or Disconnected Callback to CA adapter.
93  */
94 static CAKeepAliveConnectionCallback g_connKeepAliveCallback = NULL;
95
96 static CAResult_t CATCPPacketReceivedCB(const CASecureEndpoint_t *sep,
97                                         const void *data, uint32_t dataLength);
98
99 static void CATCPErrorHandler(const CAEndpoint_t *endpoint, const void *data,
100                               size_t dataLength, CAResult_t result);
101
102 static CAResult_t CATCPInitializeQueueHandles();
103
104 static void CATCPDeinitializeQueueHandles();
105
106 static void CATCPSendDataThread(void *threadData);
107
108 static CATCPData *CACreateTCPData(const CAEndpoint_t *remoteEndpoint,
109                                   const void *data, size_t dataLength,
110                                   bool isMulticast);
111 void CAFreeTCPData(CATCPData *ipData);
112
113 static void CADataDestroyer(void *data, uint32_t size);
114
115 CAResult_t CATCPInitializeQueueHandles()
116 {
117     // Check if the message queue is already initialized
118     if (g_sendQueueHandle)
119     {
120         OIC_LOG(DEBUG, TAG, "send queue handle is already initialized!");
121         return CA_STATUS_OK;
122     }
123
124     // Create send message queue
125     g_sendQueueHandle = OICMalloc(sizeof(CAQueueingThread_t));
126     if (!g_sendQueueHandle)
127     {
128         OIC_LOG(ERROR, TAG, "Memory allocation failed!");
129         return CA_MEMORY_ALLOC_FAILED;
130     }
131
132     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_sendQueueHandle,
133                                 (const ca_thread_pool_t)caglobals.tcp.threadpool,
134                                 CATCPSendDataThread, CADataDestroyer))
135     {
136         OIC_LOG(ERROR, TAG, "Failed to Initialize send queue thread");
137         OICFree(g_sendQueueHandle);
138         g_sendQueueHandle = NULL;
139         return CA_STATUS_FAILED;
140     }
141
142     return CA_STATUS_OK;
143 }
144
145 void CATCPDeinitializeQueueHandles()
146 {
147     CAQueueingThreadDestroy(g_sendQueueHandle);
148     OICFree(g_sendQueueHandle);
149     g_sendQueueHandle = NULL;
150 }
151
152 void CATCPConnectionStateCB(const char *ipAddress, CANetworkStatus_t status)
153 {
154     (void)ipAddress;
155     (void)status;
156 }
157
158 CAResult_t CATCPPacketReceivedCB(const CASecureEndpoint_t *sep, const void *data,
159                                  uint32_t dataLength)
160 {
161     VERIFY_NON_NULL(sep, TAG, "sep is NULL");
162     VERIFY_NON_NULL(data, TAG, "data is NULL");
163
164     OIC_LOG_V(DEBUG, TAG, "Address: %s, port:%d", sep->endpoint.addr, sep->endpoint.port);
165
166     CAResult_t res = CA_STATUS_OK;
167 #ifdef SINGLE_THREAD
168     if (g_networkPacketCallback)
169     {
170         res = g_networkPacketCallback(sep, data, dataLength);
171         if (CA_STATUS_OK != res)
172         {
173             OIC_LOG(ERROR, TAG, "Error parsing CoAP data");
174         }
175     }
176 #else
177     unsigned char *buffer = (unsigned char*)data;
178     size_t bufferLen = dataLength;
179     size_t index = 0;
180
181     //get remote device information from file descriptor.
182     CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(&sep->endpoint, &index);
183     if (!svritem)
184     {
185         OIC_LOG(ERROR, TAG, "there is no connection information in list");
186         return CA_STATUS_INVALID_PARAM;
187     }
188     if (UNKNOWN == svritem->protocol)
189     {
190         OIC_LOG(ERROR, TAG, "invalid protocol type");
191         return CA_STATUS_INVALID_PARAM;
192     }
193
194     //totalLen filled only when header fully read and parsed
195     while (0 != bufferLen)
196     {
197         res = CAConstructCoAP(svritem, &buffer, &bufferLen);
198         if (CA_STATUS_OK != res)
199         {
200             OIC_LOG_V(ERROR, TAG, "CAConstructCoAP return error : %d", res);
201             return res;
202         }
203
204         //when successfully read all required data - pass them to upper layer.
205         if (svritem->len == svritem->totalLen)
206         {
207             if (g_networkPacketCallback)
208             {
209                 res = g_networkPacketCallback(sep, svritem->data, svritem->totalLen);
210                 if (CA_STATUS_OK != res)
211                 {
212                     OIC_LOG(ERROR, TAG, "Error parsing CoAP data");
213                     return res;
214                 }
215             }
216             CACleanData(svritem);
217         }
218         else
219         {
220             OIC_LOG_V(DEBUG, TAG, "%u bytes required for complete CoAP",
221                                 svritem->totalLen - svritem->len);
222         }
223     }
224 #endif
225     return res;
226 }
227
228 #ifdef __WITH_TLS__
229 static ssize_t CATCPPacketSendCB(CAEndpoint_t *endpoint, const void *data, size_t dataLength)
230 {
231     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
232     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", -1);
233     VERIFY_NON_NULL_RET(data, TAG, "data is NULL", -1);
234
235     OIC_LOG_V(DEBUG, TAG, "Address: %s, port:%d", endpoint->addr, endpoint->port);
236     OIC_LOG_BUFFER(DEBUG, TAG, data, dataLength);
237
238     ssize_t ret = CATCPSendData(endpoint, data, dataLength);
239     OIC_LOG_V(DEBUG, TAG, "Out %s : %d bytes sent", __func__, ret);
240     return ret;
241 }
242 #endif
243
244 static void CATCPErrorHandler(const CAEndpoint_t *endpoint, const void *data,
245                               size_t dataLength, CAResult_t result)
246 {
247     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
248     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
249
250     if (g_errorCallback)
251     {
252         g_errorCallback(endpoint, data, dataLength, result);
253     }
254 }
255
256 static void CATCPConnectionHandler(const CAEndpoint_t *endpoint, bool isConnected, bool isClient)
257 {
258     // Pass the changed connection status to RI Layer for keepalive.
259     if (g_connKeepAliveCallback)
260     {
261         g_connKeepAliveCallback(endpoint, isConnected, isClient);
262     }
263
264     // Pass the changed connection status to CAUtil.
265     if (g_connectionChangeCallback)
266     {
267         g_connectionChangeCallback(endpoint, isConnected);
268     }
269 }
270
271 void CATCPSetKeepAliveCallbacks(CAKeepAliveConnectionCallback ConnHandler)
272 {
273     g_connKeepAliveCallback = ConnHandler;
274 }
275
276 void CATCPAdapterHandler(CATransportAdapter_t adapter, CANetworkStatus_t status)
277 {
278     if (g_networkChangeCallback)
279     {
280         g_networkChangeCallback(adapter, status);
281     }
282
283     if (CA_INTERFACE_DOWN == status)
284     {
285         OIC_LOG(INFO, TAG, "Network status is down, close all session");
286
287         CAResult_t res = CAQueueingThreadClearData(g_sendQueueHandle);
288         if (res != CA_STATUS_OK)
289         {
290             OIC_LOG_V(ERROR, TAG, "CAQueueingThreadClearData failed[%d]", res);
291         }
292
293         CATCPStopServer();
294     }
295     else if (CA_INTERFACE_UP == status)
296     {
297         OIC_LOG(INFO, TAG, "Network status is up, create new socket for listening");
298
299         CAResult_t ret = CA_STATUS_FAILED;
300 #ifndef SINGLE_THREAD
301         ret = CATCPStartServer((const ca_thread_pool_t)caglobals.tcp.threadpool);
302 #else
303         ret = CATCPStartServer();
304 #endif
305         if (CA_STATUS_OK != ret)
306         {
307             OIC_LOG_V(ERROR, TAG, "CATCPStartServer failed[%d]", ret);
308         }
309     }
310 }
311
312 static void CAInitializeTCPGlobals()
313 {
314     caglobals.tcp.ipv4.fd = -1;
315     caglobals.tcp.ipv4s.fd = -1;
316     caglobals.tcp.ipv6.fd = -1;
317     caglobals.tcp.ipv6s.fd = -1;
318
319     // Set the port number received from application.
320     caglobals.tcp.ipv4.port = caglobals.ports.tcp.u4;
321     caglobals.tcp.ipv4s.port = caglobals.ports.tcp.u4s;
322     caglobals.tcp.ipv6.port = caglobals.ports.tcp.u6;
323     caglobals.tcp.ipv6s.port = caglobals.ports.tcp.u6s;
324
325     caglobals.tcp.selectTimeout = CA_TCP_SELECT_TIMEOUT;
326     caglobals.tcp.listenBacklog = CA_TCP_LISTEN_BACKLOG;
327     caglobals.tcp.svrlist = NULL;
328
329     CATransportFlags_t flags = 0;
330     if (caglobals.client)
331     {
332         flags |= caglobals.clientFlags;
333     }
334     if (caglobals.server)
335     {
336         flags |= caglobals.serverFlags;
337     }
338
339     caglobals.tcp.ipv4tcpenabled = flags & CA_IPV4;
340     caglobals.tcp.ipv6tcpenabled = flags & CA_IPV6;
341 }
342
343 CAResult_t CAInitializeTCP(CARegisterConnectivityCallback registerCallback,
344                            CANetworkPacketReceivedCallback networkPacketCallback,
345                            CAAdapterChangeCallback netCallback,
346                            CAConnectionChangeCallback connCallback,
347                            CAErrorHandleCallback errorCallback, ca_thread_pool_t handle)
348 {
349     OIC_LOG(DEBUG, TAG, "IN");
350     VERIFY_NON_NULL(registerCallback, TAG, "registerCallback");
351     VERIFY_NON_NULL(networkPacketCallback, TAG, "networkPacketCallback");
352     VERIFY_NON_NULL(netCallback, TAG, "netCallback");
353 #ifndef SINGLE_THREAD
354     VERIFY_NON_NULL(handle, TAG, "thread pool handle");
355 #endif
356
357     g_networkChangeCallback = netCallback;
358     g_connectionChangeCallback = connCallback;
359     g_networkPacketCallback = networkPacketCallback;
360     g_errorCallback = errorCallback;
361
362     CAInitializeTCPGlobals();
363
364     CAResult_t res = CATCPCreateMutex();
365     if (CA_STATUS_OK == res)
366     {
367         res = CATCPCreateCond();
368     }
369     if (CA_STATUS_OK != res)
370     {
371         OIC_LOG(ERROR, TAG, "failed to create mutex/cond");
372         CATCPDestroyMutex();
373         CATCPDestroyCond();
374         return res;
375     }
376
377 #ifndef SINGLE_THREAD
378     caglobals.tcp.threadpool = handle;
379 #endif
380
381     CATCPSetConnectionChangedCallback(CATCPConnectionHandler);
382     CATCPSetPacketReceiveCallback(CATCPPacketReceivedCB);
383     CATCPSetErrorHandler(CATCPErrorHandler);
384
385 #ifdef __WITH_TLS__
386     CAsetSslAdapterCallbacks(CATCPPacketReceivedCB, CATCPPacketSendCB, CA_ADAPTER_TCP);
387 #endif
388
389     CAConnectivityHandler_t tcpHandler = {
390         .startAdapter = CAStartTCP,
391         .startListenServer = CAStartTCPListeningServer,
392         .stopListenServer = CAStopTCPListeningServer,
393         .startDiscoveryServer = CAStartTCPDiscoveryServer,
394         .sendData = CASendTCPUnicastData,
395         .sendDataToAll = CASendTCPMulticastData,
396         .GetnetInfo = CAGetTCPInterfaceInformation,
397         .readData = CAReadTCPData,
398         .stopAdapter = CAStopTCP,
399         .terminate = CATerminateTCP,
400         .cType = CA_ADAPTER_TCP};
401
402     registerCallback(tcpHandler);
403
404     OIC_LOG(INFO, TAG, "OUT IntializeTCP is Success");
405     return CA_STATUS_OK;
406 }
407
408 CAResult_t CAStartTCP()
409 {
410     OIC_LOG(DEBUG, TAG, "IN");
411
412 #ifndef SINGLE_THREAD
413     if (CA_STATUS_OK != CATCPInitializeQueueHandles())
414     {
415         OIC_LOG(ERROR, TAG, "Failed to Initialize Queue Handle");
416         CATerminateTCP();
417         return CA_STATUS_FAILED;
418     }
419
420     // Start send queue thread
421 #ifndef __TIZENRT__
422     if (CA_STATUS_OK != CAQueueingThreadStart(g_sendQueueHandle))
423 #else
424     if (CA_STATUS_OK != CAQueueingThreadStart(g_sendQueueHandle, "IoT_TCPSendQueue"))
425 #endif
426     {
427         OIC_LOG(ERROR, TAG, "Failed to Start Send Data Thread");
428         return CA_STATUS_FAILED;
429     }
430 #else
431     CAResult_t ret = CATCPStartServer();
432     if (CA_STATUS_OK != ret)
433     {
434         OIC_LOG_V(DEBUG, TAG, "CATCPStartServer failed[%d]", ret);
435         return ret;
436     }
437 #endif
438
439     // Start network monitoring to receive adapter status changes.
440     CAIPStartNetworkMonitor(CATCPAdapterHandler, CA_ADAPTER_TCP);
441
442     return CA_STATUS_OK;
443 }
444
445 static bool CAClearQueueEndpointDataContext(void *data, uint32_t size, void *ctx)
446 {
447     (void)size;
448
449     if (NULL == data || NULL == ctx)
450     {
451         return false;
452     }
453
454     CATCPData *tcpData = (CATCPData *)data;
455     CAEndpoint_t *endpoint = (CAEndpoint_t *)ctx;
456
457     if (NULL != tcpData && NULL != tcpData->remoteEndpoint)
458     {
459         if (strcmp(tcpData->remoteEndpoint->addr, endpoint->addr) == 0
460             && tcpData->remoteEndpoint->port == endpoint->port)
461         {
462             return true;
463         }
464     }
465     return false;
466 }
467
468 CAResult_t CATCPDisconnectSession(const CAEndpoint_t *endpoint)
469 {
470     CAResult_t res = CA_STATUS_OK;
471 #ifdef __WITH_TLS__
472     res = CAcloseSslConnection(endpoint);
473     if (CA_STATUS_OK != res)
474     {
475         OIC_LOG(ERROR, TAG, "failed to close TLS session");
476         res = CAQueueingThreadClearContextData(g_sendQueueHandle,
477                                                CAClearQueueEndpointDataContext,
478                                                endpoint);
479         if (CA_STATUS_OK != res)
480         {
481             OIC_LOG(ERROR, TAG, "failed to clear context data");
482         }
483
484         return res;
485     }
486 #endif
487
488     res = CASearchAndDeleteTCPSession(endpoint);
489     if (CA_STATUS_OK != res)
490     {
491         OIC_LOG(ERROR, TAG, "failed to close TCP session");
492     }
493
494     res = CAQueueingThreadClearContextData(g_sendQueueHandle,
495                                            CAClearQueueEndpointDataContext,
496                                            endpoint);
497     if (CA_STATUS_OK != res)
498     {
499         OIC_LOG(ERROR, TAG, "failed to clear context data");
500     }
501
502     return res;
503 }
504
505 CAResult_t CAStartTCPListeningServer()
506 {
507 #ifndef SINGLE_THREAD
508     if (!caglobals.server)
509     {
510         caglobals.server = true;    // only needed to run CA tests
511     }
512
513     CAResult_t ret = CATCPStartServer((const ca_thread_pool_t)caglobals.tcp.threadpool);
514     if (CA_STATUS_OK != ret)
515     {
516         OIC_LOG_V(ERROR, TAG, "Failed to start listening server![%d]", ret);
517         return ret;
518     }
519 #endif
520
521     return CA_STATUS_OK;
522 }
523
524 CAResult_t CAStopTCPListeningServer()
525 {
526     return CA_STATUS_OK;
527 }
528
529 CAResult_t CAStartTCPDiscoveryServer()
530 {
531     if (!caglobals.client)
532     {
533         caglobals.client = true;    // only needed to run CA tests
534     }
535
536     CAResult_t ret = CATCPStartServer((const ca_thread_pool_t)caglobals.tcp.threadpool);
537     if (CA_STATUS_OK != ret)
538     {
539         OIC_LOG_V(ERROR, TAG, "Failed to start discovery server![%d]", ret);
540         return ret;
541     }
542
543     return CA_STATUS_OK;
544 }
545
546 static size_t CAQueueTCPData(bool isMulticast, const CAEndpoint_t *endpoint,
547                              const void *data, size_t dataLength)
548 {
549     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint", -1);
550     VERIFY_NON_NULL_RET(data, TAG, "data", -1);
551
552     if (0 == dataLength)
553     {
554         OIC_LOG(ERROR, TAG, "Invalid Data Length");
555         return -1;
556     }
557
558     VERIFY_NON_NULL_RET(g_sendQueueHandle, TAG, "sendQueueHandle", -1);
559
560     // Create TCPData to add to queue
561     CATCPData *tcpData = CACreateTCPData(endpoint, data, dataLength, isMulticast);
562     if (!tcpData)
563     {
564         OIC_LOG(ERROR, TAG, "Failed to create ipData!");
565         return -1;
566     }
567     // Add message to send queue
568     CAQueueingThreadAddData(g_sendQueueHandle, tcpData, sizeof(CATCPData));
569
570     return dataLength;
571 }
572
573 int32_t CASendTCPUnicastData(const CAEndpoint_t *endpoint,
574                              const void *data, uint32_t dataLength,
575                              CADataType_t dataType)
576 {
577     OIC_LOG(DEBUG, TAG, "IN");
578     (void)dataType;
579 #ifndef SINGLE_THREAD
580     return CAQueueTCPData(false, endpoint, data, dataLength);
581 #else
582     return CATCPSendData(endpoint, data, dataLength);
583 #endif
584 }
585
586 int32_t CASendTCPMulticastData(const CAEndpoint_t *endpoint,
587                                const void *data, uint32_t dataLength,
588                                CADataType_t dataType)
589 {
590     (void)dataType;
591     return CAQueueTCPData(true, endpoint, data, dataLength);
592 }
593
594 CAResult_t CAReadTCPData()
595 {
596     OIC_LOG(DEBUG, TAG, "IN");
597 #ifdef SINGLE_THREAD
598     CATCPPullData();
599 #endif
600     return CA_STATUS_OK;
601 }
602
603 CAResult_t CAStopTCP()
604 {
605     CAIPStopNetworkMonitor(CA_ADAPTER_TCP);
606
607     /* Some times send queue thread fails to terminate as it's worker
608        thread gets blocked at TCP session's socket connect operation.
609        So closing sockets which are in connect operation at the time
610        of termination of adapter would save send queue thread from
611        getting blocked. */
612     CATCPCloseInProgressConnections();
613
614 #ifndef SINGLE_THREAD
615     // Stop send queue thread.
616     if (g_sendQueueHandle && g_sendQueueHandle->threadMutex)
617     {
618         CAQueueingThreadStop(g_sendQueueHandle);
619     }
620     CATCPDeinitializeQueueHandles();
621 #endif
622
623     // Close TCP servers and established connections.
624     CATCPStopServer();
625
626     // Re-initializing the Globals to start them again.
627     CAInitializeTCPGlobals();
628
629     return CA_STATUS_OK;
630 }
631
632 void CATerminateTCP()
633 {
634     CATCPSetPacketReceiveCallback(NULL);
635
636     CATCPDestroyMutex();
637     CATCPDestroyCond();
638 }
639
640 void CATCPSendDataThread(void *threadData)
641 {
642     CATCPData *tcpData = (CATCPData *) threadData;
643     if (!tcpData)
644     {
645         OIC_LOG(DEBUG, TAG, "Invalid TCP data!");
646         return;
647     }
648
649     if (caglobals.tcp.terminate)
650     {
651         OIC_LOG(DEBUG, TAG, "Adapter is not enabled");
652         CATCPErrorHandler(tcpData->remoteEndpoint, tcpData->data, tcpData->dataLen,
653                           CA_SEND_FAILED);
654         return;
655     }
656
657     if (tcpData->isMulticast)
658     {
659         //Processing for sending multicast
660         OIC_LOG(DEBUG, TAG, "Send Multicast Data is called, not supported");
661         return;
662     }
663     else
664     {
665 #ifdef __WITH_TLS__
666         if (tcpData->remoteEndpoint && tcpData->remoteEndpoint->flags & CA_SECURE)
667         {
668             CAResult_t result = CA_STATUS_OK;
669             OIC_LOG(DEBUG, TAG, "CAencryptSsl called!");
670             result = CAencryptSsl(tcpData->remoteEndpoint, tcpData->data, tcpData->dataLen);
671
672             if (CA_STATUS_OK != result)
673             {
674                 OIC_LOG(ERROR, TAG, "CAAdapterNetDtlsEncrypt failed!");
675                 CASearchAndDeleteTCPSession(tcpData->remoteEndpoint);
676                 CATCPErrorHandler(tcpData->remoteEndpoint, tcpData->data, tcpData->dataLen,
677                                   CA_SEND_FAILED);
678             }
679             OIC_LOG_V(DEBUG, TAG,
680                       "CAAdapterNetDtlsEncrypt returned with result[%d]", result);
681             return;
682         }
683 #endif
684         //Processing for sending unicast
685          ssize_t dlen = CATCPSendData(tcpData->remoteEndpoint, tcpData->data, tcpData->dataLen);
686          if (-1 == dlen)
687          {
688              OIC_LOG(ERROR, TAG, "CATCPSendData failed");
689              CASearchAndDeleteTCPSession(tcpData->remoteEndpoint);
690              CATCPErrorHandler(tcpData->remoteEndpoint, tcpData->data, tcpData->dataLen,
691                                CA_SEND_FAILED);
692          }
693     }
694 }
695
696 CATCPData *CACreateTCPData(const CAEndpoint_t *remoteEndpoint, const void *data,
697                            size_t dataLength, bool isMulticast)
698 {
699     VERIFY_NON_NULL_RET(remoteEndpoint, TAG, "remoteEndpoint is NULL", NULL);
700     VERIFY_NON_NULL_RET(data, TAG, "data is NULL", NULL);
701
702     CATCPData *tcpData = (CATCPData *) OICCalloc(1, sizeof(*tcpData));
703     if (!tcpData)
704     {
705         OIC_LOG(ERROR, TAG, "Memory allocation failed!");
706         return NULL;
707     }
708
709     tcpData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
710     tcpData->data = (void *) OICMalloc(dataLength);
711     if (!tcpData->data)
712     {
713         OIC_LOG(ERROR, TAG, "Memory allocation failed!");
714         CAFreeTCPData(tcpData);
715         return NULL;
716     }
717
718     memcpy(tcpData->data, data, dataLength);
719     tcpData->dataLen = dataLength;
720
721     tcpData->isMulticast = isMulticast;
722
723     return tcpData;
724 }
725
726 void CAFreeTCPData(CATCPData *tcpData)
727 {
728     VERIFY_NON_NULL_VOID(tcpData, TAG, "tcpData is NULL");
729
730     CAFreeEndpoint(tcpData->remoteEndpoint);
731     OICFree(tcpData->data);
732     OICFree(tcpData);
733 }
734
735 void CADataDestroyer(void *data, uint32_t size)
736 {
737     if (size < sizeof(CATCPData))
738     {
739 #ifndef __TIZENRT__
740         OIC_LOG_V(ERROR, TAG, "Destroy data too small %p %" PRIu32, data, size);
741 #endif
742     }
743     CATCPData *TCPData = (CATCPData *) data;
744
745     CAFreeTCPData(TCPData);
746 }
747
748 #ifdef SINGLE_THREAD
749 size_t CAGetTotalLengthFromPacketHeader(const unsigned char *recvBuffer, size_t size)
750 {
751     OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
752
753     if (NULL == recvBuffer || !size)
754     {
755         OIC_LOG(ERROR, TAG, "recvBuffer is NULL");
756         return 0;
757     }
758
759     coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
760             ((unsigned char *)recvBuffer)[0] >> 4);
761     size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
762                                                         transport);
763     size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
764
765     OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%d]", optPaylaodLen);
766     OIC_LOG_V(DEBUG, TAG, "header length [%d]", headerLen);
767     OIC_LOG_V(DEBUG, TAG, "total data length [%d]", headerLen + optPaylaodLen);
768
769     OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
770     return headerLen + optPaylaodLen;
771 }
772
773 void CAGetTCPHeaderDetails(unsigned char* recvBuffer, coap_transport_t *transport,
774                            size_t *headerlen)
775 {
776     if (NULL == recvBuffer)
777     {
778         OIC_LOG(ERROR, TAG, "recvBuffer is NULL");
779         return;
780     }
781
782     if (NULL == transport)
783     {
784         OIC_LOG(ERROR, TAG, "transport is NULL");
785         return;
786     }
787
788     if (NULL == headerlen)
789     {
790         OIC_LOG(ERROR, TAG, "headerlen is NULL");
791         return;
792     }
793
794     *transport = coap_get_tcp_header_type_from_initbyte(
795         ((unsigned char *)recvBuffer)[0] >> 4);
796     *headerlen = coap_get_tcp_header_length_for_transport(*transport);
797 }
798 #endif