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