[IOT-1548] Fix to transfer a large size of data on CoAPs over TCP
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / tcp_adapter / catcpserver.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 <sys/types.h>
22 #include <sys/socket.h>
23 #include <sys/select.h>
24 #include <sys/ioctl.h>
25 #include <sys/poll.h>
26 #include <stdio.h>
27 #include <unistd.h>
28 #include <fcntl.h>
29 #include <arpa/inet.h>
30 #include <netinet/in.h>
31 #include <net/if.h>
32 #include <errno.h>
33
34 #ifndef WITH_ARDUINO
35 #include <sys/socket.h>
36 #include <netinet/in.h>
37 #include <netdb.h>
38 #endif
39
40 #include "catcpinterface.h"
41 #include "caipnwmonitor.h"
42 #include <coap/pdu.h>
43 #include "caadapterutils.h"
44 #include "camutex.h"
45 #include "oic_malloc.h"
46
47 #ifdef __WITH_TLS__
48 #include "ca_adapter_net_ssl.h"
49 #endif
50
51 /**
52  * Logging tag for module name.
53  */
54 #define TAG "OIC_CA_TCP_SERVER"
55
56 /**
57  * Maximum CoAP over TCP header length
58  * to know the total data length.
59  */
60 #define COAP_MAX_HEADER_SIZE  6
61
62 /**
63  * TLS header size
64  */
65 #define TLS_HEADER_SIZE 5
66
67 /**
68  * Mutex to synchronize device object list.
69  */
70 static ca_mutex g_mutexObjectList = NULL;
71
72 /**
73  * Conditional mutex to synchronize.
74  */
75 static ca_cond g_condObjectList = NULL;
76
77 /**
78  * Maintains the callback to be notified when data received from remote device.
79  */
80 static CATCPPacketReceivedCallback g_packetReceivedCallback = NULL;
81
82 /**
83  * Error callback to update error in TCP.
84  */
85 static CATCPErrorHandleCallback g_tcpErrorHandler = NULL;
86
87 /**
88  * Connected Callback to pass the connection information to RI.
89  */
90 static CATCPConnectionHandleCallback g_connectionCallback = NULL;
91
92 static CAResult_t CATCPCreateMutex();
93 static void CATCPDestroyMutex();
94 static CAResult_t CATCPCreateCond();
95 static void CATCPDestroyCond();
96 static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock);
97 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock);
98 static void CAFindReadyMessage();
99 static void CASelectReturned(fd_set *readFds);
100 static void CAReceiveMessage(int fd);
101 static void CAReceiveHandler(void *data);
102 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem);
103
104 #define CHECKFD(FD) \
105     if (FD > caglobals.tcp.maxfd) \
106         caglobals.tcp.maxfd = FD;
107
108 #define CLOSE_SOCKET(TYPE) \
109     if (caglobals.tcp.TYPE.fd != OC_INVALID_SOCKET) \
110     { \
111         close(caglobals.tcp.TYPE.fd); \
112         caglobals.tcp.TYPE.fd = OC_INVALID_SOCKET; \
113     }
114
115 #define CA_FD_SET(TYPE, FDS) \
116     if (caglobals.tcp.TYPE.fd != OC_INVALID_SOCKET) \
117     { \
118         FD_SET(caglobals.tcp.TYPE.fd, FDS); \
119     }
120
121 /**
122  * Read length amount of data from socket item->fd
123  * Can read less data length then requested
124  * Actual read length added to item->len variable
125  *
126  * @param[in/out] item - used socket, buffer and to update received message length
127  * @param[in]  length  - length of data required to read
128  * @param[in]  flags   - additional info about socket
129  * @return             - CA_STATUS_OK or appropriate error code
130  */
131 static CAResult_t CARecv(CATCPSessionInfo_t *item, size_t length, int flags)
132 {
133     if (NULL == item)
134     {
135         return CA_STATUS_INVALID_PARAM;
136     }
137
138     //skip read operation if requested zero length
139     if (0 == length)
140     {
141         return CA_STATUS_OK;
142     }
143
144     unsigned char *buffer = item->data + item->len;
145
146     int len = recv(item->fd, buffer, length, flags);
147
148     if (len < 0)
149     {
150         OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno));
151         return CA_RECEIVE_FAILED;
152     }
153     else if (0 == len)
154     {
155         OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
156         item->state = DISCONNECTED;
157         return CA_DESTINATION_DISCONNECTED;
158     }
159
160     OIC_LOG_V(DEBUG, TAG, "recv len = %d", len);
161     OIC_LOG_BUFFER(DEBUG, TAG, buffer, len);
162
163     item->len += len;
164
165     return CA_STATUS_OK;
166 }
167
168 static void CATCPDestroyMutex()
169 {
170     if (g_mutexObjectList)
171     {
172         ca_mutex_free(g_mutexObjectList);
173         g_mutexObjectList = NULL;
174     }
175 }
176
177 static CAResult_t CATCPCreateMutex()
178 {
179     if (!g_mutexObjectList)
180     {
181         g_mutexObjectList = ca_mutex_new();
182         if (!g_mutexObjectList)
183         {
184             OIC_LOG(ERROR, TAG, "Failed to created mutex!");
185             return CA_STATUS_FAILED;
186         }
187     }
188
189     return CA_STATUS_OK;
190 }
191
192 static void CATCPDestroyCond()
193 {
194     if (g_condObjectList)
195     {
196         ca_cond_free(g_condObjectList);
197         g_condObjectList = NULL;
198     }
199 }
200
201 static CAResult_t CATCPCreateCond()
202 {
203     if (!g_condObjectList)
204     {
205         g_condObjectList = ca_cond_new();
206         if (!g_condObjectList)
207         {
208             OIC_LOG(ERROR, TAG, "Failed to created cond!");
209             return CA_STATUS_FAILED;
210         }
211     }
212     return CA_STATUS_OK;
213 }
214
215 static void CAReceiveHandler(void *data)
216 {
217     (void)data;
218     OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler");
219
220     while (!caglobals.tcp.terminate)
221     {
222         CAFindReadyMessage();
223     }
224
225     ca_mutex_lock(g_mutexObjectList);
226     ca_cond_signal(g_condObjectList);
227     ca_mutex_unlock(g_mutexObjectList);
228
229     OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
230 }
231
232 static void CAFindReadyMessage()
233 {
234     fd_set readFds;
235     struct timeval timeout = { .tv_sec = caglobals.tcp.selectTimeout };
236
237     FD_ZERO(&readFds);
238     CA_FD_SET(ipv4, &readFds);
239     CA_FD_SET(ipv6, &readFds);
240
241     if (OC_INVALID_SOCKET != caglobals.tcp.shutdownFds[0])
242     {
243         FD_SET(caglobals.tcp.shutdownFds[0], &readFds);
244     }
245     if (OC_INVALID_SOCKET != caglobals.tcp.connectionFds[0])
246     {
247         FD_SET(caglobals.tcp.connectionFds[0], &readFds);
248     }
249
250     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
251     for (size_t i = 0; i < length; i++)
252     {
253         CATCPSessionInfo_t *svritem =
254                 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
255         if (svritem && 0 <= svritem->fd && CONNECTED == svritem->state)
256         {
257             FD_SET(svritem->fd, &readFds);
258         }
259     }
260
261     int ret = select(caglobals.tcp.maxfd + 1, &readFds, NULL, NULL, &timeout);
262
263     if (caglobals.tcp.terminate)
264     {
265         OIC_LOG_V(DEBUG, TAG, "Packet receiver Stop request received.");
266         return;
267     }
268
269     if (0 < ret)
270     {
271         CASelectReturned(&readFds);
272     }
273     else if (0 > ret)
274     {
275         OIC_LOG_V(FATAL, TAG, "select error %s", strerror(errno));
276     }
277 }
278
279 static void CASelectReturned(fd_set *readFds)
280 {
281     VERIFY_NON_NULL_VOID(readFds, TAG, "readFds is NULL");
282
283     if (caglobals.tcp.ipv4.fd != -1 && FD_ISSET(caglobals.tcp.ipv4.fd, readFds))
284     {
285         CAAcceptConnection(CA_IPV4, &caglobals.tcp.ipv4);
286         return;
287     }
288     else if (caglobals.tcp.ipv6.fd != -1 && FD_ISSET(caglobals.tcp.ipv6.fd, readFds))
289     {
290         CAAcceptConnection(CA_IPV6, &caglobals.tcp.ipv6);
291         return;
292     }
293     else if (-1 != caglobals.tcp.connectionFds[0] &&
294             FD_ISSET(caglobals.tcp.connectionFds[0], readFds))
295     {
296         // new connection was created from remote device.
297         // exit the function to update read file descriptor.
298         char buf[MAX_ADDR_STR_SIZE_CA] = {0};
299         ssize_t len = read(caglobals.tcp.connectionFds[0], buf, sizeof (buf));
300         if (-1 == len)
301         {
302             return;
303         }
304         OIC_LOG_V(DEBUG, TAG, "Received new connection event with [%s]", buf);
305         FD_CLR(caglobals.tcp.connectionFds[0], readFds);
306         return;
307     }
308     else
309     {
310         uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
311         for (size_t i = 0; i < length; i++)
312         {
313             CATCPSessionInfo_t *svritem =
314                     (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
315             if (svritem && svritem->fd >= 0)
316             {
317                 if (FD_ISSET(svritem->fd, readFds))
318                 {
319                     CAReceiveMessage(svritem->fd);
320                     if (-1 != svritem->fd)
321                     {
322                         FD_CLR(svritem->fd, readFds);
323                     }
324                 }
325             }
326         }
327     }
328 }
329
330 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock)
331 {
332     VERIFY_NON_NULL_VOID(sock, TAG, "sock is NULL");
333
334     struct sockaddr_storage clientaddr;
335     socklen_t clientlen = sizeof (struct sockaddr_in);
336     if (flag & CA_IPV6)
337     {
338         clientlen = sizeof(struct sockaddr_in6);
339     }
340
341     CASocketFd_t sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen);
342     if (OC_INVALID_SOCKET != sockfd)
343     {
344         CATCPSessionInfo_t *svritem =
345                 (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
346         if (!svritem)
347         {
348             OIC_LOG(ERROR, TAG, "Out of memory");
349             close(sockfd);
350             return;
351         }
352
353         svritem->fd = sockfd;
354         svritem->sep.endpoint.flags = flag;
355         svritem->sep.endpoint.adapter = CA_ADAPTER_TCP;
356         svritem->state = CONNECTED;
357         CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
358                             svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
359
360         ca_mutex_lock(g_mutexObjectList);
361         bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem);
362         if (!result)
363         {
364             OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
365             close(sockfd);
366             OICFree(svritem);
367             ca_mutex_unlock(g_mutexObjectList);
368             return;
369         }
370         ca_mutex_unlock(g_mutexObjectList);
371
372         CHECKFD(sockfd);
373     }
374 }
375
376 #ifdef __WITH_TLS__
377 static bool CAIsTlsMessage(const unsigned char* data, size_t length)
378 {
379     if (NULL == data || 0 == length)
380     {
381         OIC_LOG_V(ERROR, TAG, "%s: null input param", __func__);
382         return false;
383     }
384
385     unsigned char first_byte = data[0];
386
387     //TLS Plaintext has four types: change_cipher_spec = [14], alert = [15],
388     //handshake = [16], application_data = [17] in HEX
389     const uint8_t tls_head_type[] = {0x14, 0x15, 0x16, 0x17};
390     size_t i = 0;
391
392     for (i = 0; i < sizeof(tls_head_type); i++)
393     {
394         if(tls_head_type[i] == first_byte)
395         {
396             return true;
397         }
398     }
399
400     return false;
401 }
402 #endif
403
404 /**
405  * Clean socket state data
406  *
407  * @param[in/out] item - socket state data
408  */
409 void CACleanData(CATCPSessionInfo_t *svritem)
410 {
411     if (svritem)
412     {
413         OICFree(svritem->data);
414         svritem->data = NULL;
415         svritem->len = 0;
416         svritem->tlsLen = 0;
417         svritem->totalLen = 0;
418         svritem->protocol = UNKNOWN;
419     }
420 }
421
422 /**
423  * Construct CoAP header and payload from buffer
424  *
425  * @param[in] svritem - used socket, buffer, current received message length and protocol
426  * @param[in/out]  data  - data buffer, this value is updated as data is copied to svritem
427  * @param[in/out]  dataLength  - length of data, this value decreased as data is copied to svritem
428  * @return             - CA_STATUS_OK or appropriate error code
429  */
430 CAResult_t CAConstructCoAP(CATCPSessionInfo_t *svritem, unsigned char **data,
431                           size_t *dataLength)
432 {
433     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
434
435     if (NULL == svritem || NULL == data || NULL == dataLength)
436     {
437         OIC_LOG(ERROR, TAG, "Invalid input parameter(NULL)");
438         return CA_STATUS_INVALID_PARAM;
439     }
440
441     unsigned char *inBuffer = *data;
442     size_t inLen = *dataLength;
443     OIC_LOG_V(DEBUG, TAG, "before-datalength : %u", *dataLength);
444
445     if (NULL == svritem->data && inLen > 0)
446     {
447         // allocate memory for message header (CoAP header size because it is bigger)
448         svritem->data = (unsigned char *) OICCalloc(1, COAP_MAX_HEADER_SIZE);
449         if (NULL == svritem->data)
450         {
451             OIC_LOG(ERROR, TAG, "OICCalloc - out of memory");
452             return CA_MEMORY_ALLOC_FAILED;
453         }
454
455         // copy 1 byte to parse coap header length
456         memcpy(svritem->data, inBuffer, 1);
457         svritem->len = 1;
458         inBuffer++;
459         inLen--;
460     }
461
462     //if not enough data received - read them on next CAFillHeader() call
463     if (0 == inLen)
464     {
465         return CA_STATUS_OK;
466     }
467
468     //if enough data received - parse header
469     svritem->protocol = COAP;
470
471     //seems CoAP data received. read full coap header.
472     coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(svritem->data[0] >> 4);
473     size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
474     size_t copyLen = 0;
475
476     // HEADER
477     if (svritem->len < headerLen)
478     {
479         copyLen = headerLen - svritem->len;
480         if (inLen < copyLen)
481         {
482             copyLen = inLen;
483         }
484
485         //read required bytes to have full CoAP header
486         memcpy(svritem->data + svritem->len, inBuffer, copyLen);
487         svritem->len += copyLen;
488         inBuffer += copyLen;
489         inLen -= copyLen;
490
491         //if not enough data received - read them on next CAFillHeader() call
492         if (svritem->len < headerLen)
493         {
494             *data = inBuffer;
495             *dataLength = inLen;
496             OIC_LOG(DEBUG, TAG, "CoAP header received partially. Wait for rest header data");
497             return CA_STATUS_OK;
498         }
499
500         //calculate CoAP message length
501         svritem->totalLen = CAGetTotalLengthFromHeader(svritem->data);
502
503         // allocate required memory
504         unsigned char *buffer = OICRealloc(svritem->data, svritem->totalLen);
505         if (NULL == buffer)
506         {
507             OIC_LOG(ERROR, TAG, "OICRealloc - out of memory");
508             return CA_MEMORY_ALLOC_FAILED;
509         }
510         svritem->data = buffer;
511     }
512
513     // PAYLOAD
514     if (inLen > 0)
515     {
516         // read required bytes to have full CoAP payload
517         copyLen = svritem->totalLen - svritem->len;
518         if (inLen < copyLen)
519         {
520             copyLen = inLen;
521         }
522
523         //read required bytes to have full CoAP header
524         memcpy(svritem->data + svritem->len, inBuffer, copyLen);
525         svritem->len += copyLen;
526         inBuffer += copyLen;
527         inLen -= copyLen;
528     }
529
530     *data = inBuffer;
531     *dataLength = inLen;
532
533     OIC_LOG_V(DEBUG, TAG, "after-datalength : %u", *dataLength);
534     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
535     return CA_STATUS_OK;
536 }
537
538 /**
539  * Read message header from socket item->fd
540  *
541  * @param[in/out] item - used socket, buffer, current received message length and protocol
542  * @return             - CA_STATUS_OK or appropriate error code
543  */
544 static CAResult_t CAReadHeader(CATCPSessionInfo_t *svritem)
545 {
546     CAResult_t res = CA_STATUS_OK;
547
548     if (NULL == svritem)
549     {
550         return CA_STATUS_INVALID_PARAM;
551     }
552
553     if (NULL == svritem->data)
554     {
555         // allocate memory for message header (CoAP header size because it is bigger)
556         svritem->data = (unsigned char *) OICCalloc(1, COAP_MAX_HEADER_SIZE);
557         if (NULL == svritem->data)
558         {
559             OIC_LOG(ERROR, TAG, "OICCalloc - out of memory");
560             return CA_MEMORY_ALLOC_FAILED;
561         }
562     }
563
564     //read data (assume TLS header) from remote device.
565     //use TLS_HEADER_SIZE - svritem->len because even header can be read partially
566     res = CARecv(svritem, TLS_HEADER_SIZE - svritem->len, 0);
567
568     //return if any error occurs
569     if (CA_STATUS_OK != res)
570     {
571         return res;
572     }
573
574     //if not enough data received - read them on next CAReceiveMessage() call
575     if (svritem->len < TLS_HEADER_SIZE)
576     {
577         OIC_LOG(DEBUG, TAG, "Header received partially. Wait for rest header data");
578         return CA_STATUS_OK;
579     }
580
581     //if enough data received - parse header
582 #ifdef __WITH_TLS__
583     if (CAIsTlsMessage(svritem->data, svritem->len))
584     {
585         svritem->protocol = TLS;
586
587         //[3][4] bytes in tls header are tls payload length
588         unsigned int message_length = (unsigned int)((svritem->data[3] << 8) | svritem->data[4]);
589         OIC_LOG_V(DEBUG, TAG, "%s: message_length = %d", __func__, message_length);
590
591         svritem->totalLen = message_length + TLS_HEADER_SIZE;
592     }
593     else
594 #endif
595     {
596         svritem->protocol = COAP;
597
598         //seems CoAP data received. read full coap header.
599         coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(svritem->data[0] >> 4);
600
601         size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
602
603         if (svritem->len < headerLen)
604         {
605             //read required bytes to have full CoAP header
606             //it should be 1 byte (COAP_MAX_HEADER_SIZE - TLS_HEADER_SIZE)
607             res = CARecv(svritem, headerLen - svritem->len, 0);
608
609             //return if any error occurs
610             if (CA_STATUS_OK != res)
611             {
612                 return res;
613             }
614
615             //if not enough data received - read them on next CAReceiveMessage() call
616             if (svritem->len < headerLen)
617             {
618                 OIC_LOG(DEBUG, TAG, "CoAP header received partially. Wait for rest header data");
619                 return CA_STATUS_OK;
620             }
621         }
622
623         //calculate CoAP message length
624         svritem->totalLen = CAGetTotalLengthFromHeader(svritem->data);
625     }
626
627     unsigned char *buffer = OICRealloc(svritem->data, svritem->totalLen);
628     if (NULL == buffer)
629     {
630         OIC_LOG(ERROR, TAG, "OICRealloc - out of memory");
631         return CA_MEMORY_ALLOC_FAILED;
632     }
633     svritem->data = buffer;
634
635     return CA_STATUS_OK;
636 }
637
638 /**
639  * Read message payload from socket item->fd
640
641  *
642  * @param[in/out] item - used socket, buffer and to update received message length
643  * @return             - CA_STATUS_OK or appropriate error code
644  */
645 static CAResult_t CAReadPayload(CATCPSessionInfo_t *svritem)
646 {
647     if (NULL == svritem)
648     {
649         return CA_STATUS_INVALID_PARAM;
650     }
651
652     return CARecv(svritem, svritem->totalLen - svritem->len, 0);
653 }
654
655 /**
656  * Pass received data to app layer depending on protocol
657  *
658  * @param[in/out] item - used buffer, received message length and protocol
659  */
660 static void CAExecuteRequest(CATCPSessionInfo_t *svritem)
661 {
662     if (NULL == svritem)
663     {
664         return;
665     }
666
667     switch(svritem->protocol)
668     {
669         case COAP:
670         {
671             if (g_packetReceivedCallback)
672             {
673                 g_packetReceivedCallback(&svritem->sep, svritem->data, svritem->len);
674             }
675         }
676         break;
677         case TLS:
678 #ifdef __WITH_TLS__
679         {
680             int ret = CAdecryptSsl(&svritem->sep, (uint8_t *)svritem->data, svritem->len);
681
682             OIC_LOG_V(DEBUG, TAG, "%s: CAdecryptSsl returned %d", __func__, ret);
683         }
684         break;
685 #endif
686         case UNKNOWN: /* pass through */
687         default:
688             OIC_LOG(ERROR, TAG, "unknown application protocol. Ignore it");
689         break;
690     }
691 }
692
693 static void CAReceiveMessage(int fd)
694 {
695     CAResult_t res = CA_STATUS_OK;
696
697     //get remote device information from file descriptor.
698     size_t index = 0;
699     CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFD(fd, &index);
700     if (!svritem)
701     {
702         OIC_LOG(ERROR, TAG, "there is no connection information in list");
703         return;
704     }
705
706     // read data
707     int len = 0;
708
709     if (svritem->sep.endpoint.flags & CA_SECURE)
710     {
711         svritem->protocol = TLS;
712
713 #ifdef __WITH_TLS__
714         size_t nbRead = 0;
715         size_t tlsLength = 0;
716
717         if (TLS_HEADER_SIZE > svritem->tlsLen)
718         {
719             nbRead = TLS_HEADER_SIZE - svritem->tlsLen;
720         }
721         else
722         {
723             //[3][4] bytes in tls header are tls payload length
724             tlsLength = TLS_HEADER_SIZE +
725                             (size_t)((svritem->tlsdata[3] << 8) | svritem->tlsdata[4]);
726             OIC_LOG_V(DEBUG, TAG, "toal tls length = %u", tlsLength);
727             if (tlsLength > sizeof(svritem->tlsdata))
728             {
729                 OIC_LOG_V(ERROR, TAG, "toal tls length is too big (buffer size : %u)",
730                                     sizeof(svritem->tlsdata));
731                 return CA_STATUS_FAILED;
732             }
733             nbRead = tlsLength - svritem->tlsLen;
734         }
735
736         len = recv(fd, svritem->tlsdata + svritem->tlsLen, nbRead, 0);
737         if (len < 0)
738         {
739             OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno));
740             res = CA_RECEIVE_FAILED;
741         }
742         else if (0 == len)
743         {
744             OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
745             res = CA_DESTINATION_DISCONNECTED;
746         }
747         else
748         {
749             svritem->tlsLen += len;
750             OIC_LOG_V(DEBUG, TAG, "nb_read : %u bytes , recv() : %d bytes, svritem->tlsLen : %u bytes",
751                                 nbRead, len, svritem->tlsLen);
752             if (tlsLength > 0 && tlsLength == svritem->tlsLen)
753             {
754                 //when successfully read data - pass them to callback.
755                 res = CAdecryptSsl(&svritem->sep, (uint8_t *)svritem->tlsdata, svritem->tlsLen);
756                 svritem->tlsLen = 0;
757                 OIC_LOG_V(DEBUG, TAG, "%s: CAdecryptSsl returned %d", __func__, res);
758             }
759         }
760 #endif
761
762     }
763     else
764     {
765         unsigned char buffer[65535] = {0,}; // 65535 is the maximum size of ip packet
766         svritem->protocol = COAP;
767
768         len = recv(fd, buffer, sizeof(buffer), 0);
769         if (len < 0)
770         {
771             OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno));
772             res = CA_RECEIVE_FAILED;
773         }
774         else if (0 == len)
775         {
776             OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
777             res = CA_DESTINATION_DISCONNECTED;
778         }
779         else
780         {
781             OIC_LOG_V(DEBUG, TAG, "recv() : %d bytes", len);
782             //when successfully read data - pass them to callback.
783             if (g_packetReceivedCallback)
784             {
785                 g_packetReceivedCallback(&svritem->sep, buffer, len);
786             }
787         }
788     }
789
790     //disconnect session and clean-up data if any error occurs
791     if (res != CA_STATUS_OK)
792     {
793 #ifdef __WITH_TLS__
794         if (CA_STATUS_OK != CAcloseSslConnection(&svritem->sep.endpoint))
795         {
796             OIC_LOG(ERROR, TAG, "Failed to close TLS session");
797         }
798 #endif
799         CASearchAndDeleteTCPSession(&(svritem->sep.endpoint));
800         return;
801     }
802 }
803
804 static ssize_t CAWakeUpForReadFdsUpdate(const char *host)
805 {
806     if (caglobals.tcp.connectionFds[1] != -1)
807     {
808         ssize_t len = 0;
809         do
810         {
811             len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
812         } while ((len == -1) && (errno == EINTR));
813
814         if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
815         {
816             OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
817         }
818         return len;
819     }
820     return -1;
821 }
822
823 static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port,
824                                          struct sockaddr_storage *sockaddr)
825 {
826     struct addrinfo *addrs = NULL;
827     struct addrinfo hints = { .ai_family = family,
828                               .ai_protocol   = IPPROTO_TCP,
829                               .ai_socktype = SOCK_STREAM,
830                               .ai_flags = AI_NUMERICHOST };
831
832     int r = getaddrinfo(host, NULL, &hints, &addrs);
833     if (r)
834     {
835         if (EAI_SYSTEM == r)
836         {
837             OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: errno %s", strerror(errno));
838         }
839         else
840         {
841             OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: %s", gai_strerror(r));
842         }
843         freeaddrinfo(addrs);
844         return CA_STATUS_FAILED;
845     }
846     // assumption: in this case, getaddrinfo will only return one addrinfo
847     // or first is the one we want.
848     if (addrs[0].ai_family == AF_INET6)
849     {
850         memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6));
851         ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port);
852     }
853     else
854     {
855         memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in));
856         ((struct sockaddr_in *)sockaddr)->sin_port = htons(port);
857     }
858     freeaddrinfo(addrs);
859     return CA_STATUS_OK;
860 }
861
862 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
863 {
864     VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
865
866     OIC_LOG_V(DEBUG, TAG, "try to connect with [%s:%u]",
867               svritem->sep.endpoint.addr, svritem->sep.endpoint.port);
868
869     // #1. create tcp socket.
870     int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
871     if (-1 == fd)
872     {
873         OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
874         return CA_SOCKET_OPERATION_FAILED;
875     }
876     svritem->fd = fd;
877
878     // #2. convert address from string to binary.
879     struct sockaddr_storage sa = { .ss_family = family };
880     CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr,
881                                             svritem->sep.endpoint.port, &sa);
882     if (CA_STATUS_OK != res)
883     {
884         OIC_LOG(ERROR, TAG, "convert name to sockaddr failed");
885         return CA_SOCKET_OPERATION_FAILED;
886     }
887
888     // #3. set socket length.
889     socklen_t socklen = 0;
890     if (sa.ss_family == AF_INET6)
891     {
892         struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
893         if (!sock6->sin6_scope_id)
894         {
895             sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
896         }
897         socklen = sizeof(struct sockaddr_in6);
898     }
899     else
900     {
901         socklen = sizeof(struct sockaddr_in);
902     }
903
904     // #4. connect to remote server device.
905     if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
906     {
907         OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
908         return CA_SOCKET_OPERATION_FAILED;
909     }
910
911     OIC_LOG(DEBUG, TAG, "connect socket success");
912     svritem->state = CONNECTED;
913     CHECKFD(svritem->fd);
914     ssize_t len = CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
915     if (-1 == len)
916     {
917         OIC_LOG(ERROR, TAG, "wakeup receive thread failed");
918         return CA_SOCKET_OPERATION_FAILED;
919     }
920     return CA_STATUS_OK;
921 }
922
923 static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock)
924 {
925     VERIFY_NON_NULL_RET(sock, TAG, "sock", -1);
926
927     if (OC_INVALID_SOCKET != sock->fd)
928     {
929         OIC_LOG(DEBUG, TAG, "accept socket created already");
930         return sock->fd;
931     }
932
933     socklen_t socklen = 0;
934     struct sockaddr_storage server = { .ss_family = family };
935
936     int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
937     if (OC_INVALID_SOCKET == fd)
938     {
939         OIC_LOG(ERROR, TAG, "Failed to create socket");
940         goto exit;
941     }
942
943     if (family == AF_INET6)
944     {
945         // the socket is restricted to sending and receiving IPv6 packets only.
946         int on = 1;
947         if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
948         {
949             OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
950             goto exit;
951         }
952         ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port);
953         socklen = sizeof (struct sockaddr_in6);
954     }
955     else
956     {
957         ((struct sockaddr_in *)&server)->sin_port = htons(sock->port);
958         socklen = sizeof (struct sockaddr_in);
959     }
960
961     int reuse = 1;
962     if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
963     {
964         OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
965         goto exit;
966     }
967
968     if (-1 == bind(fd, (struct sockaddr *)&server, socklen))
969     {
970         OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
971         goto exit;
972     }
973
974     if (listen(fd, caglobals.tcp.listenBacklog) != 0)
975     {
976         OIC_LOG(ERROR, TAG, "listen() error");
977         goto exit;
978     }
979
980     if (!sock->port)  // return the assigned port
981     {
982         if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen))
983         {
984             OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
985             goto exit;
986         }
987         sock->port = ntohs(family == AF_INET6 ?
988                       ((struct sockaddr_in6 *)&server)->sin6_port :
989                       ((struct sockaddr_in *)&server)->sin_port);
990     }
991
992     return fd;
993
994 exit:
995     if (fd >= 0)
996     {
997         close(fd);
998     }
999     return OC_INVALID_SOCKET;
1000 }
1001
1002 static void CAInitializePipe(int *fds)
1003 {
1004     int ret = pipe(fds);
1005     if (-1 != ret)
1006     {
1007         ret = fcntl(fds[0], F_GETFD);
1008         if (-1 != ret)
1009         {
1010             ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
1011         }
1012         if (-1 != ret)
1013         {
1014             ret = fcntl(fds[1], F_GETFD);
1015         }
1016         if (-1 != ret)
1017         {
1018             ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
1019         }
1020         if (-1 == ret)
1021         {
1022             close(fds[1]);
1023             close(fds[0]);
1024
1025             fds[0] = -1;
1026             fds[1] = -1;
1027
1028             OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
1029         }
1030     }
1031 }
1032
1033 #define NEWSOCKET(FAMILY, NAME) \
1034     caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
1035     if (caglobals.tcp.NAME.fd == -1) \
1036     { \
1037         caglobals.tcp.NAME.port = 0; \
1038         caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
1039     } \
1040     CHECKFD(caglobals.tcp.NAME.fd);
1041
1042 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
1043 {
1044     if (caglobals.tcp.started)
1045     {
1046         OIC_LOG(DEBUG, TAG, "Adapter is started already");
1047         return CA_STATUS_OK;
1048     }
1049
1050     if (!caglobals.tcp.ipv4tcpenabled)
1051     {
1052         caglobals.tcp.ipv4tcpenabled = true;    // only needed to run CA tests
1053     }
1054     if (!caglobals.tcp.ipv6tcpenabled)
1055     {
1056         caglobals.tcp.ipv6tcpenabled = true;    // only needed to run CA tests
1057     }
1058
1059     CAResult_t res = CATCPCreateMutex();
1060     if (CA_STATUS_OK == res)
1061     {
1062         res = CATCPCreateCond();
1063     }
1064     if (CA_STATUS_OK != res)
1065     {
1066         OIC_LOG(ERROR, TAG, "failed to create mutex/cond");
1067         return res;
1068     }
1069
1070     ca_mutex_lock(g_mutexObjectList);
1071     if (!caglobals.tcp.svrlist)
1072     {
1073         caglobals.tcp.svrlist = u_arraylist_create();
1074     }
1075     ca_mutex_unlock(g_mutexObjectList);
1076
1077     if (caglobals.server)
1078     {
1079         NEWSOCKET(AF_INET, ipv4);
1080         NEWSOCKET(AF_INET6, ipv6);
1081         OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
1082                   caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
1083         OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
1084                   caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
1085     }
1086
1087     // create pipe for fast shutdown
1088     CAInitializePipe(caglobals.tcp.shutdownFds);
1089     CHECKFD(caglobals.tcp.shutdownFds[0]);
1090     CHECKFD(caglobals.tcp.shutdownFds[1]);
1091
1092     // create pipe for connection event
1093     CAInitializePipe(caglobals.tcp.connectionFds);
1094     CHECKFD(caglobals.tcp.connectionFds[0]);
1095     CHECKFD(caglobals.tcp.connectionFds[1]);
1096
1097     caglobals.tcp.terminate = false;
1098     res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
1099     if (CA_STATUS_OK != res)
1100     {
1101         OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
1102         return res;
1103     }
1104     OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
1105
1106     caglobals.tcp.started = true;
1107     return CA_STATUS_OK;
1108 }
1109
1110 void CATCPStopServer()
1111 {
1112     if (caglobals.tcp.terminate)
1113     {
1114         OIC_LOG(DEBUG, TAG, "Adapter is not enabled");
1115         return;
1116     }
1117
1118     // mutex lock
1119     ca_mutex_lock(g_mutexObjectList);
1120
1121     // set terminate flag.
1122     caglobals.tcp.terminate = true;
1123
1124     if (caglobals.tcp.shutdownFds[1] != -1)
1125     {
1126         close(caglobals.tcp.shutdownFds[1]);
1127         caglobals.tcp.shutdownFds[1] = OC_INVALID_SOCKET;
1128         // receive thread will stop immediately
1129     }
1130     if (caglobals.tcp.connectionFds[1] != -1)
1131     {
1132         close(caglobals.tcp.connectionFds[1]);
1133         caglobals.tcp.connectionFds[1] = OC_INVALID_SOCKET;
1134     }
1135
1136     // close accept socket.
1137     CLOSE_SOCKET(ipv4);
1138     CLOSE_SOCKET(ipv6);
1139
1140     if (caglobals.tcp.started)
1141     {
1142         ca_cond_wait(g_condObjectList, g_mutexObjectList);
1143     }
1144     caglobals.tcp.started = false;
1145
1146     // mutex unlock
1147     ca_mutex_unlock(g_mutexObjectList);
1148
1149     CATCPDisconnectAll();
1150     CATCPDestroyMutex();
1151     CATCPDestroyCond();
1152
1153     OIC_LOG(DEBUG, TAG, "Adapter terminated successfully");
1154 }
1155
1156 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
1157 {
1158     g_packetReceivedCallback = callback;
1159 }
1160
1161 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
1162 {
1163     g_connectionCallback = connHandler;
1164 }
1165
1166 size_t CACheckPayloadLengthFromHeader(const void *data, size_t dlen)
1167 {
1168     VERIFY_NON_NULL_RET(data, TAG, "data", -1);
1169
1170     coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1171             ((unsigned char *)data)[0] >> 4);
1172
1173     coap_pdu_t *pdu = coap_new_pdu2(transport, dlen);
1174     if (!pdu)
1175     {
1176         OIC_LOG(ERROR, TAG, "outpdu is null");
1177         return 0;
1178     }
1179
1180     int ret = coap_pdu_parse2((unsigned char *) data, dlen, pdu, transport);
1181     if (0 >= ret)
1182     {
1183         OIC_LOG(ERROR, TAG, "pdu parse failed");
1184         coap_delete_pdu(pdu);
1185         return 0;
1186     }
1187
1188     size_t payloadLen = 0;
1189     size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
1190     OIC_LOG_V(DEBUG, TAG, "headerSize : %zu, pdu length : %d",
1191               headerSize, pdu->length);
1192     if (pdu->length > headerSize)
1193     {
1194         payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
1195     }
1196
1197     OICFree(pdu);
1198
1199     return payloadLen;
1200 }
1201
1202 static ssize_t sendData(const CAEndpoint_t *endpoint, const void *data,
1203                         size_t dlen, const char *fam)
1204 {
1205     OIC_LOG_V(INFO, TAG, "The length of data that needs to be sent is %zu bytes", dlen);
1206
1207     // #1. find a session info from list.
1208     CASocketFd_t sockFd = CAGetSocketFDFromEndpoint(endpoint);
1209     if (OC_INVALID_SOCKET == sockFd)
1210     {
1211         // if there is no connection info, connect to remote device.
1212         sockFd = CAConnectTCPSession(endpoint);
1213         if (OC_INVALID_SOCKET == sockFd)
1214         {
1215             OIC_LOG(ERROR, TAG, "Failed to create tcp session object");
1216             return -1;
1217         }
1218     }
1219
1220     // #2. send data to remote device.
1221     ssize_t remainLen = dlen;
1222     do
1223     {
1224         ssize_t len = send(sockFd, data, remainLen, 0);
1225         if (-1 == len)
1226         {
1227             if (EWOULDBLOCK != errno)
1228             {
1229                 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
1230                 return len;
1231             }
1232             continue;
1233         }
1234         data += len;
1235         remainLen -= len;
1236     } while (remainLen > 0);
1237
1238 #ifndef TB_LOG
1239     (void)fam;
1240 #endif
1241     OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
1242     return dlen;
1243 }
1244
1245 ssize_t CATCPSendData(CAEndpoint_t *endpoint, const void *data, size_t datalen)
1246 {
1247     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", -1);
1248     VERIFY_NON_NULL_RET(data, TAG, "data is NULL", -1);
1249
1250     if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
1251     {
1252         return sendData(endpoint, data, datalen, "ipv6");
1253     }
1254     if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
1255     {
1256         return sendData(endpoint, data, datalen, "ipv4");
1257     }
1258
1259     OIC_LOG(ERROR, TAG, "Not supported transport flags");
1260     return -1;
1261 }
1262
1263 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1264 {
1265     VERIFY_NON_NULL(info, TAG, "info is NULL");
1266     VERIFY_NON_NULL(size, TAG, "size is NULL");
1267
1268     return CA_NOT_SUPPORTED;
1269 }
1270
1271 CASocketFd_t CAConnectTCPSession(const CAEndpoint_t *endpoint)
1272 {
1273     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1274
1275     // #1. create TCP server object
1276     CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
1277     if (!svritem)
1278     {
1279         OIC_LOG(ERROR, TAG, "Out of memory");
1280         return OC_INVALID_SOCKET;
1281     }
1282     memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
1283     svritem->sep.endpoint.adapter = endpoint->adapter;
1284     svritem->sep.endpoint.port = endpoint->port;
1285     svritem->sep.endpoint.flags = endpoint->flags;
1286     svritem->sep.endpoint.ifindex = endpoint->ifindex;
1287     svritem->state = CONNECTING;
1288
1289     // #2. add TCP connection info to list
1290     ca_mutex_lock(g_mutexObjectList);
1291     if (caglobals.tcp.svrlist)
1292     {
1293         bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
1294         if (!res)
1295         {
1296             OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
1297             close(svritem->fd);
1298             OICFree(svritem);
1299             ca_mutex_unlock(g_mutexObjectList);
1300             return OC_INVALID_SOCKET;
1301         }
1302     }
1303     ca_mutex_unlock(g_mutexObjectList);
1304
1305     // #3. create the socket and connect to TCP server
1306     int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
1307     if (CA_STATUS_OK != CATCPCreateSocket(family, svritem))
1308     {
1309         return OC_INVALID_SOCKET;
1310     }
1311
1312     // #4. pass the connection information to CA Common Layer.
1313     if (g_connectionCallback)
1314     {
1315         g_connectionCallback(&(svritem->sep.endpoint), true);
1316     }
1317
1318     return svritem->fd;
1319 }
1320
1321 CAResult_t CADisconnectTCPSession(size_t index)
1322 {
1323     CATCPSessionInfo_t *removedData = u_arraylist_remove(caglobals.tcp.svrlist, index);
1324     if (!removedData)
1325     {
1326         OIC_LOG(DEBUG, TAG, "there is no data to be removed");
1327         return CA_STATUS_OK;
1328     }
1329
1330     // close the socket and remove session info in list.
1331     if (removedData->fd >= 0)
1332     {
1333         shutdown(removedData->fd, SHUT_RDWR);
1334         close(removedData->fd);
1335         removedData->fd = -1;
1336         removedData->state = (CONNECTED == removedData->state) ?
1337                                     DISCONNECTED : removedData->state;
1338
1339         // pass the connection information to CA Common Layer.
1340         if (g_connectionCallback && DISCONNECTED == removedData->state)
1341         {
1342             g_connectionCallback(&(removedData->sep.endpoint), false);
1343         }
1344     }
1345     OICFree(removedData->data);
1346     removedData->data = NULL;
1347
1348     OICFree(removedData);
1349     removedData = NULL;
1350
1351     OIC_LOG(DEBUG, TAG, "data is removed from session list");
1352     return CA_STATUS_OK;
1353 }
1354
1355 void CATCPDisconnectAll()
1356 {
1357     ca_mutex_lock(g_mutexObjectList);
1358
1359     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1360     for (ssize_t index = length; index > 0; index--)
1361     {
1362         // disconnect session from remote device.
1363         CADisconnectTCPSession(index - 1);
1364     }
1365
1366     u_arraylist_destroy(caglobals.tcp.svrlist);
1367     caglobals.tcp.svrlist = NULL;
1368
1369     ca_mutex_unlock(g_mutexObjectList);
1370
1371 #ifdef __WITH_TLS__
1372     CAcloseSslConnectionAll();
1373 #endif
1374
1375 }
1376
1377 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
1378 {
1379     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1380     VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
1381
1382     OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1383
1384     // get connection info from list
1385     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1386     for (size_t i = 0; i < length; i++)
1387     {
1388         CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1389                 caglobals.tcp.svrlist, i);
1390         if (!svritem)
1391         {
1392             continue;
1393         }
1394
1395         if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1396                      sizeof(svritem->sep.endpoint.addr))
1397                 && (svritem->sep.endpoint.port == endpoint->port)
1398                 && (svritem->sep.endpoint.flags & endpoint->flags))
1399         {
1400             OIC_LOG(DEBUG, TAG, "Found in session list");
1401             *index = i;
1402             return svritem;
1403         }
1404     }
1405
1406     OIC_LOG(DEBUG, TAG, "Session not found");
1407     return NULL;
1408 }
1409
1410 CASocketFd_t CAGetSocketFDFromEndpoint(const CAEndpoint_t *endpoint)
1411 {
1412     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1413
1414     OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1415
1416     // get connection info from list.
1417     ca_mutex_lock(g_mutexObjectList);
1418     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1419     for (size_t i = 0; i < length; i++)
1420     {
1421         CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1422                 caglobals.tcp.svrlist, i);
1423         if (!svritem)
1424         {
1425             continue;
1426         }
1427
1428         if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1429                      sizeof(svritem->sep.endpoint.addr))
1430                 && (svritem->sep.endpoint.port == endpoint->port)
1431                 && (svritem->sep.endpoint.flags & endpoint->flags))
1432         {
1433             ca_mutex_unlock(g_mutexObjectList);
1434             OIC_LOG(DEBUG, TAG, "Found in session list");
1435             return svritem->fd;
1436         }
1437     }
1438
1439     ca_mutex_unlock(g_mutexObjectList);
1440     OIC_LOG(DEBUG, TAG, "Session not found");
1441     return OC_INVALID_SOCKET;
1442 }
1443
1444 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1445 {
1446     ca_mutex_lock(g_mutexObjectList);
1447
1448     // check from the last item.
1449     CATCPSessionInfo_t *svritem = NULL;
1450     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1451     for (size_t i = 0; i < length; i++)
1452     {
1453         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1454
1455         if (svritem && svritem->fd == fd)
1456         {
1457             *index = i;
1458             ca_mutex_unlock(g_mutexObjectList);
1459             return svritem;
1460         }
1461     }
1462
1463     ca_mutex_unlock(g_mutexObjectList);
1464
1465     return NULL;
1466 }
1467
1468 CAResult_t CASearchAndDeleteTCPSession(const CAEndpoint_t *endpoint)
1469 {
1470     ca_mutex_lock(g_mutexObjectList);
1471
1472     CAResult_t result = CA_STATUS_OK;
1473     size_t index = 0;
1474     CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1475     if (svritem)
1476     {
1477         result = CADisconnectTCPSession(index);
1478         if (CA_STATUS_OK != result)
1479         {
1480             OIC_LOG_V(ERROR, TAG, "CADisconnectTCPSession failed, result[%d]", result);
1481         }
1482     }
1483
1484     ca_mutex_unlock(g_mutexObjectList);
1485     return result;
1486 }
1487
1488 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1489 {
1490     OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1491
1492     coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1493             ((unsigned char *)recvBuffer)[0] >> 4);
1494     size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1495                                                         transport);
1496     size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1497
1498     OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%zu]", optPaylaodLen);
1499     OIC_LOG_V(DEBUG, TAG, "header length [%zu]", headerLen);
1500     OIC_LOG_V(DEBUG, TAG, "total data length [%zu]", headerLen + optPaylaodLen);
1501
1502     OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1503     return headerLen + optPaylaodLen;
1504 }
1505
1506 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1507 {
1508     g_tcpErrorHandler = errorHandleCallback;
1509 }
1510