Change the header install path for c_common and logger
[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/ioctl.h>
24 #if defined(__TIZEN__)
25 #include <ifaddrs.h>
26 #endif
27 #ifdef __TIZENRT__
28 #include <tinyara/config.h>
29 #include <poll.h>
30 #else
31 #include <sys/poll.h>
32 #endif
33 #include <stdio.h>
34 #include <unistd.h>
35 #include <fcntl.h>
36 #include <arpa/inet.h>
37 #include <netinet/in.h>
38 #include <netinet/tcp.h>
39 #include <net/if.h>
40 #include <errno.h>
41
42 #ifndef WITH_ARDUINO
43 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #include <netdb.h>
46 #endif
47
48 #include "catcpinterface.h"
49 #include "caipnwmonitor.h"
50 #include <coap/pdu.h>
51 #include "caadapterutils.h"
52 #include "octhread.h"
53 #include "oic_malloc.h"
54 #include "oic_string.h"
55
56 #ifdef __WITH_TLS__
57 #include "ca_adapter_net_ssl.h"
58 #endif
59
60 /**
61  * Logging tag for module name.
62  */
63 //#define TAG "OIC_CA_TCP_SERVER"
64 #define TAG TCP_SERVER_TAG
65
66 /**
67  * Maximum CoAP over TCP header length
68  * to know the total data length.
69  */
70 #define COAP_MAX_HEADER_SIZE  6
71
72 /**
73  * TLS header size
74  */
75 #define TLS_HEADER_SIZE 5
76
77 /**
78  * Max Connection Counts.
79  */
80 #define MAX_CONNECTION_COUNTS   500
81
82 #define COAP_TCP_MAX_BUFFER_CHUNK_SIZE 65530 //64kb - 6 (coap+tcp max header size)
83
84 #define MILLISECONDS_PER_SECOND   (1000)
85
86 /**
87  * Thread pool.
88  */
89 static ca_thread_pool_t g_threadPool = NULL;
90
91 /**
92  * Thread task id.
93  */
94 static uint32_t g_taskId = 0;
95
96 /**
97  * Mutex to synchronize device object list.
98  */
99 static oc_mutex g_mutexObjectList = NULL;
100
101 /**
102  * Conditional mutex to synchronize.
103  */
104 static oc_cond g_condObjectList = NULL;
105
106 /**
107  * Mutex to synchronize send.
108  */
109 static oc_mutex g_mutexSend = NULL;
110
111 /**
112  * Conditional mutex to synchronize send.
113  */
114 static oc_cond g_condSend = NULL;
115
116 /**
117  * Maintains the callback to be notified when data received from remote device.
118  */
119 static CATCPPacketReceivedCallback g_packetReceivedCallback = NULL;
120
121 /**
122  * Error callback to update error in TCP.
123  */
124 static CATCPErrorHandleCallback g_tcpErrorHandler = NULL;
125
126 /**
127  * Connected Callback to pass the connection information to RI.
128  */
129 static CATCPConnectionHandleCallback g_connectionCallback = NULL;
130
131 /**
132  * Error code to hold the errno(Timeout, Destination unreachable, etc) when send/recv fails.
133  * Main purpose is to hold the reason for connection drop when keep-alive is in use.
134  * To indicate normal disconnection, 0 will be assigned.
135  */
136 static int g_lastErrorCode;
137
138 static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock);
139 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock);
140 static void CAFindReadyMessage();
141 static void CAPollReturned(struct pollfd *readFds, size_t size);
142 static void CAReceiveMessage(int fd);
143 static void CAReceiveHandler(void *data);
144 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem);
145 static void CATCPInitializeSocket();
146 static CATCPSessionInfo_t *CAGetSessionInfoFromFDAsOwner(int fd, size_t *index);
147
148 #if defined(__TIZEN__)
149 static char g_cloudproxyUri[CA_MAX_URI_LENGTH];
150
151 static char g_interfaceName[CA_MAX_INTERFACE_NAME_LEN];
152
153 CAResult_t CASetCloudAddressForProxy(const char *uri)
154 {
155     if (uri == NULL)
156         memset(g_cloudproxyUri, '\0', sizeof (g_cloudproxyUri));
157     else
158         OICStrcpy(g_cloudproxyUri, sizeof (g_cloudproxyUri), uri);
159     return CA_STATUS_OK;
160 }
161
162 const char *CAGetCloudAddressForProxy()
163 {
164     if (g_cloudproxyUri[0] == '\0')
165         return NULL;
166     return g_cloudproxyUri;
167 }
168
169 CAResult_t CASetTCPServerSocketBindIP(const char* ifname)
170 {
171     CAResult_t res = CA_STATUS_OK;
172 #ifdef TCP_ADAPTER
173     VERIFY_NON_NULL_RET(ifname, TAG, "Interface name is NULL", CA_STATUS_INVALID_PARAM);
174
175     OIC_LOG(DEBUG, TAG, "Setting Socket Bind");
176     caglobals.tcp.bindenabled = true;
177     OICStrcpy(g_interfaceName, sizeof (g_interfaceName), ifname);
178 #else
179     OIC_LOG(DEBUG, TAG, "Not supported!");
180     res = CA_NOT_SUPPORTED;
181 #endif
182     return res;
183 }
184 #endif
185
186 #define MAX_TCP_SOCK_COUNT 4
187
188 #define CLOSE_SOCKET(TYPE) \
189     if (caglobals.tcp.TYPE.fd != OC_INVALID_SOCKET) \
190     { \
191         close(caglobals.tcp.TYPE.fd); \
192         caglobals.tcp.TYPE.fd = OC_INVALID_SOCKET; \
193     }
194
195 #define CA_FD_SET(TYPE, FDS, COUNT) \
196         FDS[COUNT].fd = caglobals.tcp.TYPE.fd; \
197         FDS[COUNT].events = POLLIN;
198
199 void CATCPDestroyMutex()
200 {
201     if (g_mutexObjectList)
202     {
203         oc_mutex_free(g_mutexObjectList);
204         g_mutexObjectList = NULL;
205     }
206 }
207
208 CAResult_t CATCPCreateMutex()
209 {
210     if (!g_mutexObjectList)
211     {
212         g_mutexObjectList = oc_mutex_new_recursive();
213         if (!g_mutexObjectList)
214         {
215             OIC_LOG(ERROR, TAG, "Failed to create mutex!");
216             return CA_STATUS_FAILED;
217         }
218     }
219
220     return CA_STATUS_OK;
221 }
222
223 void CATCPDestroyCond()
224 {
225     if (g_condObjectList)
226     {
227         oc_cond_free(g_condObjectList);
228         g_condObjectList = NULL;
229     }
230 }
231
232 CAResult_t CATCPCreateCond()
233 {
234     if (!g_condObjectList)
235     {
236         g_condObjectList = oc_cond_new();
237         if (!g_condObjectList)
238         {
239             OIC_LOG(ERROR, TAG, "Failed to create cond!");
240             return CA_STATUS_FAILED;
241         }
242     }
243     return CA_STATUS_OK;
244 }
245
246 void CATCPDestroySendMutex()
247 {
248     if (g_mutexSend)
249     {
250         oc_mutex_free(g_mutexSend);
251         g_mutexSend = NULL;
252     }
253 }
254
255 CAResult_t CATCPCreateSendMutex()
256 {
257     if (!g_mutexSend)
258     {
259         g_mutexSend = oc_mutex_new();
260         if (!g_mutexSend)
261         {
262             OIC_LOG(ERROR, TAG, "Failed to create send mutex!");
263             return CA_STATUS_FAILED;
264         }
265     }
266
267     return CA_STATUS_OK;
268 }
269
270 void CATCPDestroySendCond()
271 {
272     if (g_condSend)
273     {
274         oc_cond_free(g_condSend);
275         g_condSend = NULL;
276     }
277 }
278
279 CAResult_t CATCPCreateSendCond()
280 {
281     if (!g_condSend)
282     {
283         g_condSend = oc_cond_new();
284         if (!g_condSend)
285         {
286             OIC_LOG(ERROR, TAG, "Failed to create send cond!");
287             return CA_STATUS_FAILED;
288         }
289     }
290     return CA_STATUS_OK;
291 }
292
293 static void CAReceiveHandler(void *data)
294 {
295     (void)data;
296     OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler");
297
298     while (true)
299     {
300         oc_mutex_lock(g_mutexObjectList);
301         if (caglobals.tcp.terminate)
302         {
303             oc_mutex_unlock(g_mutexObjectList);
304             break;
305         }
306         oc_mutex_unlock(g_mutexObjectList);
307         CAFindReadyMessage();
308     }
309
310     oc_mutex_lock(g_mutexObjectList);
311     oc_cond_signal(g_condObjectList);
312     oc_mutex_unlock(g_mutexObjectList);
313
314     OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
315 }
316
317 static void CAFindReadyMessage()
318 {
319     int timeout = (caglobals.tcp.selectTimeout * 1000);
320     size_t counter = 0;
321
322     oc_mutex_lock(g_mutexObjectList);
323     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
324
325     // Consider 4 tcp sockets(ipv4, ipv4s, ipv6, ipv6s) + 1 connection fd + all sockets in svrlist
326     struct pollfd *readFds = (struct pollfd *)OICCalloc(MAX_TCP_SOCK_COUNT + 1 + length, sizeof(struct pollfd));
327     if (NULL == readFds)
328     {
329         OIC_LOG_V(ERROR, TAG, "Failed to allocate memory!");
330         oc_mutex_unlock(g_mutexObjectList);
331         return;
332     }
333
334     // 4 tcp sockets
335     CA_FD_SET(ipv4, readFds, counter);
336     counter++;
337     CA_FD_SET(ipv4s, readFds, counter);
338     counter++;
339     CA_FD_SET(ipv6, readFds, counter);
340     counter++;
341     CA_FD_SET(ipv6s, readFds, counter);
342     counter++;
343
344     // 1 connection fd
345     readFds[counter].fd = caglobals.tcp.connectionFds[0];
346     readFds[counter].events = POLLIN;
347     counter++;
348
349     // All sockets in svrlist
350     for (size_t i = 0; i < length; i++)
351     {
352         CATCPSessionInfo_t *svritem =
353                 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
354         if (svritem && 0 <= svritem->fd && CONNECTED == svritem->state)
355         {
356             readFds[counter].fd = svritem->fd;
357             readFds[counter].events = POLLIN;
358             counter++;
359         }
360     }
361     oc_mutex_unlock(g_mutexObjectList);
362     int ret = poll(readFds, counter, timeout);
363
364     oc_mutex_lock(g_mutexObjectList);
365     if (caglobals.tcp.terminate)
366     {
367         OIC_LOG_V(INFO, TAG, "Packet receiver Stop request received.");
368         oc_mutex_unlock(g_mutexObjectList);
369         OICFree(readFds);
370         return;
371     }
372     oc_mutex_unlock(g_mutexObjectList);
373
374     if (ret > 0)
375     {
376         CAPollReturned(readFds, counter);
377     }
378     else if (ret == 0)
379     {
380         usleep(1000); /* some of the fields are not set by kernel on repeatedly calling
381                          poll.Applying a sleep will solve this by providing a delay between
382                          each subsequent poll system call */
383     }
384     else if (ret < 0)
385     {
386         OIC_LOG_V(FATAL, TAG, "poll error %s", strerror(errno));
387     }
388
389     OICFree(readFds);
390 }
391
392 static void CAPollReturned(struct pollfd *readFds, size_t size)
393 {
394     VERIFY_NON_NULL_VOID(readFds, TAG, "readFds is NULL");
395
396     if (caglobals.tcp.ipv4.fd != -1 && readFds[0].revents == POLLIN)
397     {
398         CAAcceptConnection(CA_IPV4, &caglobals.tcp.ipv4);
399         return;
400     }
401     else if (caglobals.tcp.ipv4s.fd != -1 && readFds[1].revents == POLLIN)
402     {
403         CAAcceptConnection(CA_IPV4 | CA_SECURE, &caglobals.tcp.ipv4s);
404         return;
405     }
406     else if (caglobals.tcp.ipv6.fd != -1 && readFds[2].revents == POLLIN)
407     {
408         CAAcceptConnection(CA_IPV6, &caglobals.tcp.ipv6);
409         return;
410     }
411     else if (caglobals.tcp.ipv6s.fd != -1 && readFds[3].revents == POLLIN)
412     {
413         CAAcceptConnection(CA_IPV6 | CA_SECURE, &caglobals.tcp.ipv6s);
414         return;
415     }
416     else if (-1 != caglobals.tcp.connectionFds[0] && readFds[4].revents != 0)
417     {
418             // new connection was created from remote device.
419             // exit the function to update read file descriptor.
420             char buf[MAX_ADDR_STR_SIZE_CA] = {0};
421             ssize_t len = read(caglobals.tcp.connectionFds[0], buf, sizeof (buf));
422             if (-1 == len)
423             {
424                 return;
425             }
426             OIC_LOG_V(DEBUG, TAG, "Received new connection event with [%s]", buf);
427             return;
428     }
429     else
430     {
431         int *readFDList = NULL;
432         size_t readFDListSize = 0;
433
434         oc_mutex_lock(g_mutexObjectList);
435         uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
436
437         readFDList = (int*) OICCalloc(length, sizeof(int));
438         if (NULL == readFDList)
439         {
440             OIC_LOG_V(ERROR, TAG, "Failed to allocate memory!");
441             oc_mutex_unlock(g_mutexObjectList);
442             return;
443         }
444
445         for (size_t i = 0; i < length; i++)
446         {
447             CATCPSessionInfo_t *svritem =
448                     (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
449             if (svritem && svritem->fd >= 0)
450             {
451                 size_t j = 0;
452                 while (j < size)
453                 {
454                     if (svritem->fd == readFds[j].fd)
455                     {
456                         break;
457                     }
458                     j++;
459                 }
460
461                 if (j < size  && readFds[j].revents != 0)
462                 {
463                     readFDList[readFDListSize++] = svritem->fd;
464                 }
465             }
466         }
467         oc_mutex_unlock(g_mutexObjectList);
468
469         // Read incomming messages from fds
470         for (size_t i = 0; i < readFDListSize; i++)
471         {
472             CAReceiveMessage(readFDList[i]);
473         }
474
475         OICFree(readFDList);
476     }
477 }
478
479 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock)
480 {
481     OIC_LOG_V(INFO, TAG, "In %s", __func__);
482     VERIFY_NON_NULL_VOID(sock, TAG, "sock is NULL");
483
484     if (MAX_CONNECTION_COUNTS == u_arraylist_length(caglobals.tcp.svrlist))
485     {
486         OIC_LOG_V(INFO, TAG, "Exceeding the max connection counts limit, close listening port");
487         close(sock->fd);
488         sock->fd = OC_INVALID_SOCKET;
489         return;
490     }
491
492     struct sockaddr_storage clientaddr;
493     socklen_t clientlen = sizeof (struct sockaddr_in);
494     if (flag & CA_IPV6)
495     {
496         clientlen = sizeof(struct sockaddr_in6);
497     }
498
499     CASocketFd_t sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen);
500     if (OC_INVALID_SOCKET != sockfd)
501     {
502         CATCPSessionInfo_t *svritem =
503                 (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
504         if (!svritem)
505         {
506             OIC_LOG(ERROR, TAG, "Out of memory");
507             close(sockfd);
508             return;
509         }
510
511         svritem->fd = sockfd;
512         svritem->sep.endpoint.flags = flag;
513         svritem->sep.endpoint.adapter = CA_ADAPTER_TCP;
514         svritem->state = CONNECTED;
515         svritem->isClient = false;
516         CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
517                             svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
518
519         // Allocate message buffer
520         svritem->tlsdata = (unsigned char*) OICCalloc(TLS_DATA_MAX_SIZE, sizeof(unsigned char));
521         if (!svritem->tlsdata)
522         {
523             OIC_LOG(ERROR, TAG, "Out of memory");
524             close(sockfd);
525             OICFree(svritem);
526             return;
527         }
528
529         oc_mutex_lock(g_mutexObjectList);
530         bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem);
531         if (!result)
532         {
533             OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
534             close(sockfd);
535             OICFree(svritem->tlsdata);
536             OICFree(svritem);
537             oc_mutex_unlock(g_mutexObjectList);
538             return;
539         }
540         oc_mutex_unlock(g_mutexObjectList);
541
542         // pass the connection information to CA Common Layer.
543         if (g_connectionCallback)
544         {
545             g_connectionCallback(&(svritem->sep.endpoint), true, svritem->isClient);
546         }
547     }
548     OIC_LOG_V(INFO, TAG, "Out %s", __func__);
549 }
550
551 /**
552  * Clean socket state data
553  *
554  * @param[in/out] item - socket state data
555  */
556 void CACleanData(CATCPSessionInfo_t *svritem)
557 {
558     if (svritem)
559     {
560         OICFree(svritem->data);
561         svritem->data = NULL;
562         svritem->len = 0;
563 #ifdef __WITH_TLS__
564         svritem->tlsLen = 0;
565 #endif
566         svritem->totalLen = 0;
567         svritem->bufLen = 0;
568         svritem->protocol = UNKNOWN;
569     }
570 }
571
572 /**
573  * Construct CoAP header and payload from buffer
574  *
575  * @param[in] svritem - used socket, buffer, current received message length and protocol
576  * @param[in/out]  data  - data buffer, this value is updated as data is copied to svritem
577  * @param[in/out]  dataLength  - length of data, this value decreased as data is copied to svritem
578  * @return             - CA_STATUS_OK or appropriate error code
579  */
580 CAResult_t CAConstructCoAP(CATCPSessionInfo_t *svritem, unsigned char **data,
581                           size_t *dataLength)
582 {
583     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
584
585     if (NULL == svritem || NULL == data || NULL == dataLength)
586     {
587         OIC_LOG(ERROR, TAG, "Invalid input parameter(NULL)");
588         return CA_STATUS_INVALID_PARAM;
589     }
590
591     unsigned char *inBuffer = *data;
592     size_t inLen = *dataLength;
593     OIC_LOG_V(DEBUG, TAG, "before-datalength : %zd", *dataLength);
594
595     if (NULL == svritem->data && inLen > 0)
596     {
597         // allocate memory for message header (CoAP header size because it is bigger)
598         svritem->data = (unsigned char *) OICCalloc(1, COAP_MAX_HEADER_SIZE);
599         if (NULL == svritem->data)
600         {
601             OIC_LOG(ERROR, TAG, "OICCalloc - out of memory");
602             return CA_MEMORY_ALLOC_FAILED;
603         }
604
605         // copy 1 byte to parse coap header length
606         memcpy(svritem->data, inBuffer, 1);
607         svritem->len = 1;
608         svritem->bufLen = COAP_MAX_HEADER_SIZE;
609         inBuffer++;
610         inLen--;
611     }
612
613     //if not enough data received - read them on next CAFillHeader() call
614     if (0 == inLen)
615     {
616         return CA_STATUS_OK;
617     }
618
619     //if enough data received - parse header
620     svritem->protocol = COAP;
621
622     //seems CoAP data received. read full coap header.
623     coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(svritem->data[0] >> 4);
624     size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
625     size_t copyLen = 0;
626
627     // HEADER
628     if (svritem->len < headerLen)
629     {
630         copyLen = headerLen - svritem->len;
631         if (inLen < copyLen)
632         {
633             copyLen = inLen;
634         }
635
636         //read required bytes to have full CoAP header
637         memcpy(svritem->data + svritem->len, inBuffer, copyLen);
638         svritem->len += copyLen;
639         inBuffer += copyLen;
640         inLen -= copyLen;
641
642         //if not enough data received - read them on next CAFillHeader() call
643         if (svritem->len < headerLen)
644         {
645             *data = inBuffer;
646             *dataLength = inLen;
647             OIC_LOG(DEBUG, TAG, "CoAP header received partially. Wait for rest header data");
648             return CA_STATUS_OK;
649         }
650
651         //calculate CoAP message length
652         svritem->totalLen = CAGetTotalLengthFromHeader(svritem->data);
653     }
654
655     // PAYLOAD
656     if (inLen > 0)
657     {
658         // Calculate length of data to be copied.
659         copyLen = svritem->totalLen - svritem->len;
660         if (inLen < copyLen)
661         {
662             copyLen = inLen;
663         }
664
665         // Is buffer not big enough for remaining data ?
666         if (svritem->len + copyLen > svritem->bufLen)
667         {
668             // Resize buffer to accommodate enough space
669             size_t extLen = svritem->totalLen - svritem->bufLen;
670             if (extLen > COAP_TCP_MAX_BUFFER_CHUNK_SIZE)
671             {
672                 extLen = COAP_TCP_MAX_BUFFER_CHUNK_SIZE;
673             }
674
675             // Allocate required memory
676             unsigned char *buffer = OICRealloc(svritem->data, svritem->bufLen + extLen);
677             if (NULL == buffer)
678             {
679                 OIC_LOG(ERROR, TAG, "OICRealloc - out of memory");
680                 return CA_MEMORY_ALLOC_FAILED;
681             }
682
683             svritem->data = buffer;
684             svritem->bufLen += extLen;
685         }
686
687         // Read required bytes to have full CoAP payload
688         memcpy(svritem->data + svritem->len, inBuffer, copyLen);
689         svritem->len += copyLen;
690         inBuffer += copyLen;
691         inLen -= copyLen;
692     }
693
694     *data = inBuffer;
695     *dataLength = inLen;
696
697     OIC_LOG_V(DEBUG, TAG, "after-datalength : %zd", *dataLength);
698     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
699     return CA_STATUS_OK;
700 }
701
702 static void CAReceiveMessage(int fd)
703 {
704     CAResult_t res = CA_STATUS_OK;
705
706     oc_mutex_lock(g_mutexObjectList);
707
708     //get remote device information from file descriptor.
709     size_t index = 0;
710     CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFDAsOwner(fd, &index);
711     if (!svritem)
712     {
713         OIC_LOG(ERROR, TAG, "there is no connection information in list");
714         oc_mutex_unlock(g_mutexObjectList);
715         return;
716     }
717
718     CASecureEndpoint_t peerEP = svritem->sep;
719     int len = 0;
720     if (svritem->sep.endpoint.flags & CA_SECURE) // Secure connection
721     {
722         svritem->protocol = TLS;
723
724 #ifdef __WITH_TLS__
725         size_t nbRead = 0;
726         size_t tlsLength = 0;
727
728         if (TLS_HEADER_SIZE > svritem->tlsLen)
729         {
730             nbRead = TLS_HEADER_SIZE - svritem->tlsLen;
731         }
732         else
733         {
734             //[3][4] bytes in tls header are tls payload length
735             tlsLength = TLS_HEADER_SIZE +
736                             (size_t)((svritem->tlsdata[3] << 8) | svritem->tlsdata[4]);
737             OIC_LOG_V(DEBUG, TAG, "total tls length = %zd", tlsLength);
738             if (tlsLength > TLS_DATA_MAX_SIZE)
739             {
740                 OIC_LOG_V(ERROR, TAG, "total tls length is too big (buffer size : %u)",
741                                     TLS_DATA_MAX_SIZE);
742                 oc_mutex_unlock(g_mutexObjectList);
743                 CATCPDisconnectSession(&peerEP.endpoint);
744                 return;
745             }
746             nbRead = tlsLength - svritem->tlsLen;
747         }
748
749         len = recv(fd, svritem->tlsdata + svritem->tlsLen, nbRead, 0);
750         if (len < 0)
751         {
752             g_lastErrorCode = errno;
753             OIC_LOG_V(DEBUG, TAG, "Set g_lastErrorCode to %s", strerror(g_lastErrorCode));
754             OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(g_lastErrorCode));
755             res = CA_RECEIVE_FAILED;
756         }
757         else if (0 == len)
758         {
759             g_lastErrorCode = 0;
760             OIC_LOG(DEBUG, TAG, "Set g_lastErrorCode to 0");
761             OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
762             svritem->state = DISCONNECTED;
763             res = CA_DESTINATION_DISCONNECTED;
764         }
765         else
766         {
767             svritem->tlsLen += len;
768             OIC_LOG_V(DEBUG, TAG, "nb_read : %zd bytes , recv() : %d bytes, svritem->tlsLen : %zd bytes",
769                                 nbRead, len, svritem->tlsLen);
770             if (tlsLength > 0 && tlsLength == svritem->tlsLen)
771             {
772                 // When successfully read data - pass them to callback.
773                 // Dont invoke callback locking mutex
774                 unsigned char *mesBuf = svritem->tlsdata;
775                 size_t mesBufLen = svritem->tlsLen;
776                 svritem->tlsdata = NULL;
777                 oc_mutex_unlock(g_mutexObjectList);
778
779                 res = CAdecryptSsl(&peerEP, (uint8_t *)mesBuf, mesBufLen);
780                 OIC_LOG_V(INFO, TAG, "%s: CAdecryptSsl returned %d", __func__, res);
781
782                 // Check for the svritem and reset buffer
783                 oc_mutex_lock(g_mutexObjectList);
784                 svritem = CAGetSessionInfoFromFDAsOwner(fd, &index);
785                 if (svritem)
786                 {
787                     svritem->tlsdata = mesBuf;
788                     svritem->tlsLen = 0;
789                 }
790                 else
791                 {
792                     // svritem does not exist, thus free the message buffer
793                     OIC_LOG(ERROR, TAG, "svritem not found. Freeing message buffer!");
794                     OICFree(mesBuf);
795                 }
796             }
797         }
798 #endif
799     }
800     else // Non-Secure connection
801     {
802         svritem->protocol = COAP;
803
804         // svritem->tlsdata can also be used as receiving buffer in case of raw tcp
805         len = recv(fd, svritem->tlsdata, TLS_DATA_MAX_SIZE, 0);
806         if (len < 0)
807         {
808             g_lastErrorCode = errno;
809             OIC_LOG_V(DEBUG, TAG, "Set g_lastErrorCode to %s", strerror(g_lastErrorCode));
810             OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(g_lastErrorCode));
811             res = CA_RECEIVE_FAILED;
812         }
813         else if (0 == len)
814         {
815             g_lastErrorCode = 0;
816             OIC_LOG_V(DEBUG, TAG, "Set g_lastErrorCode to 0");
817             OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
818             res = CA_DESTINATION_DISCONNECTED;
819         }
820         else
821         {
822             //when successfully read data - pass them to callback.
823             OIC_LOG_V(DEBUG, TAG, "recv() : %d bytes", len);
824             if (g_packetReceivedCallback)
825             {
826                 // Dont invoke callback locking mutex
827                 unsigned char *mesBuf = svritem->tlsdata;
828                 svritem->tlsdata = NULL;
829                 oc_mutex_unlock(g_mutexObjectList);
830
831                 res = g_packetReceivedCallback(&peerEP, mesBuf, len);
832
833                 // Check for the svritem and reset buffer
834                 oc_mutex_lock(g_mutexObjectList);
835                 svritem = CAGetSessionInfoFromFDAsOwner(fd, &index);
836                 if (svritem)
837                 {
838                     svritem->tlsdata = mesBuf;
839                     svritem->tlsLen = 0;
840                 }
841                 else
842                 {
843                     // svritem does not exist, thus free the message buffer
844                     OIC_LOG(ERROR, TAG, "svritem not found. Freeing message buffer!");
845                     OICFree(mesBuf);
846                 }
847             }
848         }
849     }
850
851     oc_mutex_unlock(g_mutexObjectList);
852
853     if (res != CA_STATUS_OK)
854     {
855         CATCPDisconnectSession(&peerEP.endpoint);
856     }
857 }
858
859 static ssize_t CAWakeUpForReadFdsUpdate(const char *host)
860 {
861     if (caglobals.tcp.connectionFds[1] != -1)
862     {
863         ssize_t len = 0;
864         do
865         {
866             len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
867         } while ((len == -1) && (errno == EINTR));
868
869         if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
870         {
871             OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
872         }
873         return len;
874     }
875     return -1;
876 }
877
878 static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port,
879                                          struct sockaddr_storage *sockaddr)
880 {
881     struct addrinfo *addrs = NULL;
882     struct addrinfo hints = { .ai_family = family,
883                               .ai_protocol   = IPPROTO_TCP,
884                               .ai_socktype = SOCK_STREAM,
885                               .ai_flags = AI_NUMERICHOST };
886
887     int r = getaddrinfo(host, NULL, &hints, &addrs);
888     if (r)
889     {
890         if (EAI_SYSTEM == r)
891         {
892             OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: errno %s", strerror(errno));
893         }
894         else
895         {
896             OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: %s", gai_strerror(r));
897         }
898         freeaddrinfo(addrs);
899         return CA_STATUS_FAILED;
900     }
901     // assumption: in this case, getaddrinfo will only return one addrinfo
902     // or first is the one we want.
903     if (addrs[0].ai_family == AF_INET6)
904     {
905         memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6));
906         ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port);
907     }
908     else
909     {
910         memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in));
911         ((struct sockaddr_in *)sockaddr)->sin_port = htons(port);
912     }
913     freeaddrinfo(addrs);
914     return CA_STATUS_OK;
915 }
916
917 #if defined(__TIZEN__)
918 static char * CATCPGetInterfaceAddr()
919 {
920     struct ifaddrs *ifaddr, *ifa;
921     int family, s, n;
922     char *host = (uint8_t *)OICMalloc(NI_MAXHOST);
923
924     if (getifaddrs(&ifaddr) == -1)
925     {
926         OIC_LOG_V(ERROR, TAG, "getifaddrs failed: errno %s", strerror(errno));
927         OICFree(host);
928         return NULL;
929     }
930
931     for (ifa = ifaddr, n = 0; ifa != NULL; ifa = ifa->ifa_next, n++)
932     {
933         if (ifa->ifa_addr == NULL)
934             continue;
935
936         family = ifa->ifa_addr->sa_family;
937         OIC_LOG_V(DEBUG, TAG,"Interface name: %s",ifa->ifa_name);
938
939         if ((strncmp(g_interfaceName,ifa->ifa_name,strlen(ifa->ifa_name))==0)
940             && (family == AF_INET || family == AF_INET6))
941         {
942             s = getnameinfo(ifa->ifa_addr, (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6),
943                                         host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
944             if (s != 0)
945             {
946                 OIC_LOG_V(ERROR, TAG, "getnameinfo failed: errno %s", strerror(errno));
947                 freeifaddrs(ifaddr);
948                 OICFree(host);
949                 return NULL;
950             }
951
952             OIC_LOG_V(DEBUG, TAG, "Interface address: %s", host);
953             freeifaddrs(ifaddr);
954             return host;
955         }
956     }
957
958     freeifaddrs(ifaddr);
959     OICFree(host);
960     OIC_LOG(ERROR, TAG, "Interface address not found");
961     return NULL;
962 }
963 #endif
964
965 #if defined(__TIZEN__)
966 static int CAGetHTTPStatusCode(char * response) {
967     char *resp, *code_plus, *ptrSave;
968     int ret = -1;
969
970     resp = strdup(response);
971     strtok_r(resp, " ", &ptrSave);  /* skip HTTP version */
972     code_plus = strtok_r(NULL, " ", &ptrSave);
973
974     ret = code_plus ? atoi(code_plus) : -1;
975     free(resp);
976     return ret;
977 }
978 #endif
979
980 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
981 {
982     VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
983
984     OIC_LOG_V(INFO, TAG, "try to connect with [%s:%u]",
985               svritem->sep.endpoint.addr, svritem->sep.endpoint.port);
986
987     // #1. create tcp socket.
988     int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
989     if (-1 == fd)
990     {
991         OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
992         return CA_SOCKET_OPERATION_FAILED;
993     }
994     svritem->fd = fd;
995
996     // #2. convert address from string to binary.
997     struct sockaddr_storage sa = { .ss_family = family };
998     CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr,
999                                             svritem->sep.endpoint.port, &sa);
1000     if (CA_STATUS_OK != res)
1001     {
1002         OIC_LOG(ERROR, TAG, "convert name to sockaddr failed");
1003         return CA_SOCKET_OPERATION_FAILED;
1004     }
1005
1006     // #3. set socket length.
1007     socklen_t socklen = 0;
1008     if (sa.ss_family == AF_INET6)
1009     {
1010         struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
1011         if (!sock6->sin6_scope_id)
1012         {
1013             sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
1014         }
1015         socklen = sizeof(struct sockaddr_in6);
1016     }
1017     else
1018     {
1019         socklen = sizeof(struct sockaddr_in);
1020     }
1021
1022 #if defined(__TIZEN__)
1023     if (caglobals.tcp.bindenabled)
1024     {
1025         char *host_address = CATCPGetInterfaceAddr();
1026         if (host_address)
1027         {
1028             if (sa.ss_family == AF_INET)
1029             {
1030                 struct sockaddr_in client;
1031                 memset(&client, 0x00, sizeof(client));
1032                 client.sin_family = AF_INET;
1033                 inet_pton(AF_INET, host_address, &(client.sin_addr.s_addr));
1034                 if (-1 == bind(fd, (struct sockaddr *)&client, socklen))
1035                 {
1036                     OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
1037                     OICFree(host_address);
1038                     return CA_SOCKET_OPERATION_FAILED;
1039                 }
1040             }
1041             else
1042             {
1043                 struct sockaddr_in6 client6;
1044                 memset(&client6, 0x00, sizeof(client6));
1045                 client6.sin6_family = AF_INET6;
1046                 inet_pton(AF_INET6, host_address, &client6.sin6_addr.s6_addr);
1047                 if (-1 == bind(fd, (struct sockaddr *)&client6, socklen))
1048                 {
1049                     OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
1050                     OICFree(host_address);
1051                     return CA_SOCKET_OPERATION_FAILED;
1052                 }
1053             }
1054             OICFree(host_address);
1055         }
1056     }
1057 #endif
1058
1059     // #4. connect to remote server device.
1060     if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
1061     {
1062         OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
1063         CALogSendStateInfo(svritem->sep.endpoint.adapter, svritem->sep.endpoint.addr,
1064                            svritem->sep.endpoint.port, 0, false, strerror(errno));
1065         return CA_SOCKET_OPERATION_FAILED;
1066     }
1067
1068     OIC_LOG(INFO, TAG, "connect socket success");
1069     svritem->state = CONNECTED;
1070     ssize_t len = CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
1071     if (-1 == len)
1072     {
1073         OIC_LOG(ERROR, TAG, "wakeup receive thread failed");
1074         return CA_SOCKET_OPERATION_FAILED;
1075     }
1076
1077 #if defined(__TIZEN__)
1078     // #5. Send HTTP CONNECT to proxy if proxy
1079
1080     const char *cloud_address = CAGetCloudAddressForProxy();
1081     OIC_LOG_V(INFO, TAG, "Proxy : '%s'", cloud_address ? cloud_address : "(nil)");
1082
1083     if(cloud_address && *cloud_address)
1084     {
1085         char message[4096];
1086         int len = snprintf(message, 4096,
1087                 "CONNECT %s HTTP/1.1\r\n"
1088                 "Host: %s\r\n\r\n", cloud_address, cloud_address
1089         );
1090
1091         ssize_t l = send(fd, message, len, 0);
1092         if(l != len)
1093         {
1094             OIC_LOG_V(ERROR, TAG, "failed to send HTTP CONNECT data (expected %d bytes, ret %zd)", len, l);
1095             close(fd);
1096             svritem->fd = -1;
1097             return CA_SOCKET_OPERATION_FAILED;
1098         }
1099
1100         // maybe this should be called in other thread, it causes bottleneck.
1101         OIC_LOG_V(INFO, TAG, "Message sent is : '%s'\n", message);
1102
1103         *message = '\0';
1104         OIC_LOG_V(INFO, TAG, "Receiving response to CONNECT from proxy...");
1105
1106         l = recv(fd, message, 4096, 0);
1107
1108         OIC_LOG_V(INFO, TAG, "Received data : '%s'", message);
1109         OIC_LOG_V(INFO, TAG, "Received len = %zd", l);
1110
1111         int status_code = CAGetHTTPStatusCode(message);
1112
1113         OIC_LOG_V(INFO, TAG, "HTTP status_code : %d", status_code);
1114         if(status_code < 200 || status_code > 299)
1115         {
1116             OIC_LOG_V(ERROR, TAG, "Error, Wrong status code: %d", status_code);
1117             close(fd);
1118             svritem->fd = -1;
1119             return CA_SOCKET_OPERATION_FAILED;
1120         }
1121     }
1122 #endif
1123
1124     return CA_STATUS_OK;
1125 }
1126
1127 static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock)
1128 {
1129     VERIFY_NON_NULL_RET(sock, TAG, "sock", -1);
1130
1131     if (OC_INVALID_SOCKET != sock->fd)
1132     {
1133         OIC_LOG(DEBUG, TAG, "accept socket created already");
1134         return sock->fd;
1135     }
1136
1137     socklen_t socklen = 0;
1138     struct sockaddr_storage server = { .ss_family = family };
1139
1140     int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
1141     if (OC_INVALID_SOCKET == fd)
1142     {
1143         OIC_LOG(ERROR, TAG, "Failed to create socket");
1144         goto exit;
1145     }
1146
1147     if (family == AF_INET6)
1148     {
1149         // the socket is restricted to sending and receiving IPv6 packets only.
1150         int on = 1;
1151 //TODO: enable once IPv6 is supported
1152 #ifndef __TIZENRT__
1153         if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
1154         {
1155             OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
1156             goto exit;
1157         }
1158 #endif
1159         ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port);
1160         socklen = sizeof (struct sockaddr_in6);
1161     }
1162     else
1163     {
1164         ((struct sockaddr_in *)&server)->sin_port = htons(sock->port);
1165         socklen = sizeof (struct sockaddr_in);
1166     }
1167
1168     int reuse = 1;
1169     if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
1170     {
1171         OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
1172         goto exit;
1173     }
1174
1175     if (-1 == bind(fd, (struct sockaddr *)&server, socklen))
1176     {
1177         OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
1178         goto exit;
1179     }
1180
1181     if (listen(fd, caglobals.tcp.listenBacklog) != 0)
1182     {
1183         OIC_LOG(ERROR, TAG, "listen() error");
1184         goto exit;
1185     }
1186
1187     if (sock->port) // use the given port
1188     {
1189         int on = 1;
1190         if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof (on)))
1191         {
1192             OIC_LOG_V(ERROR, TAG, "SO_REUSEADDR failed: %s", strerror(errno));
1193             close(fd);
1194             return OC_INVALID_SOCKET;
1195         }
1196     }
1197     else  // return the assigned port
1198     {
1199         if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen))
1200         {
1201             OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
1202             goto exit;
1203         }
1204         sock->port = ntohs(family == AF_INET6 ?
1205                       ((struct sockaddr_in6 *)&server)->sin6_port :
1206                       ((struct sockaddr_in *)&server)->sin_port);
1207     }
1208
1209     return fd;
1210
1211 exit:
1212     if (fd >= 0)
1213     {
1214         close(fd);
1215     }
1216     return OC_INVALID_SOCKET;
1217 }
1218
1219 static void CAInitializePipe(int *fds)
1220 {
1221     int ret = pipe(fds);
1222 // TODO: Remove temporary workaround once F_GETFD / F_SETFD support is in TizenRT
1223 /* Temporary workaround: By pass F_GETFD / F_SETFD */
1224 #ifdef __TIZENRT__
1225     if (-1 == ret)
1226     {
1227         close(fds[1]);
1228         close(fds[0]);
1229
1230         fds[0] = -1;
1231         fds[1] = -1;
1232
1233         OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
1234     }
1235 #else
1236     if (-1 != ret)
1237     {
1238         ret = fcntl(fds[0], F_GETFD);
1239         if (-1 != ret)
1240         {
1241             ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
1242         }
1243         if (-1 != ret)
1244         {
1245             ret = fcntl(fds[1], F_GETFD);
1246         }
1247         if (-1 != ret)
1248         {
1249             ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
1250         }
1251         if (-1 == ret)
1252         {
1253             close(fds[1]);
1254             close(fds[0]);
1255
1256             fds[0] = -1;
1257             fds[1] = -1;
1258
1259             OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
1260         }
1261     }
1262 #endif
1263 }
1264
1265 #ifndef DISABLE_TCP_SERVER
1266 #define NEWSOCKET(FAMILY, NAME) \
1267     caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
1268     if (caglobals.tcp.NAME.fd == -1) \
1269     { \
1270         caglobals.tcp.NAME.port = 0; \
1271         caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
1272     } \
1273
1274 void CATCPInitializeSocket()
1275 {
1276 #ifndef __WITH_TLS__
1277         NEWSOCKET(AF_INET, ipv4);
1278 #else
1279         NEWSOCKET(AF_INET, ipv4s);
1280 #endif
1281
1282 //TODO Enable once TizenRT supports IPv6
1283 #ifndef __TIZENRT__
1284 #ifndef __WITH_TLS__
1285         NEWSOCKET(AF_INET6, ipv6);
1286 #else
1287         NEWSOCKET(AF_INET6, ipv6s);
1288 #endif
1289 #endif
1290 #ifndef __WITH_TLS__
1291         OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
1292                   caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
1293         OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
1294                   caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
1295 #else
1296         OIC_LOG_V(DEBUG, TAG, "IPv4 secure socket fd=%d, port=%d",
1297                   caglobals.tcp.ipv4s.fd, caglobals.tcp.ipv4s.port);
1298         OIC_LOG_V(DEBUG, TAG, "IPv6 secure socket fd=%d, port=%d",
1299                   caglobals.tcp.ipv6s.fd, caglobals.tcp.ipv6s.port);
1300 #endif
1301 }
1302 #endif // DISABLE_TCP_SERVER
1303
1304 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
1305 {
1306     oc_mutex_lock(g_mutexObjectList);
1307     if (caglobals.tcp.started)
1308     {
1309         oc_mutex_unlock(g_mutexObjectList);
1310         OIC_LOG(INFO, TAG, "Adapter is started already");
1311         return CA_STATUS_OK;
1312     }
1313
1314     g_threadPool = threadPool;
1315
1316     if (!caglobals.tcp.ipv4tcpenabled)
1317     {
1318         caglobals.tcp.ipv4tcpenabled = true;    // only needed to run CA tests
1319     }
1320     if (!caglobals.tcp.ipv6tcpenabled)
1321     {
1322         caglobals.tcp.ipv6tcpenabled = true;    // only needed to run CA tests
1323     }
1324
1325     caglobals.tcp.terminate = false;
1326     if (!caglobals.tcp.svrlist)
1327     {
1328         caglobals.tcp.svrlist = u_arraylist_create();
1329     }
1330
1331 #ifndef DISABLE_TCP_SERVER
1332     if (caglobals.server)
1333     {
1334         CATCPInitializeSocket();
1335     }
1336 #endif
1337
1338 #ifndef __TIZENRT__
1339     // create pipe for fast shutdown
1340     CAInitializePipe(caglobals.tcp.shutdownFds);
1341 #endif
1342     // create pipe for connection event
1343     CAInitializePipe(caglobals.tcp.connectionFds);
1344
1345     CAResult_t res = CA_STATUS_OK;
1346 #ifndef __TIZENRT__
1347     res = ca_thread_pool_add_task(g_threadPool, CAReceiveHandler, NULL, &g_taskId);
1348 #else
1349     res = ca_thread_pool_add_task(g_threadPool, CAReceiveHandler, NULL, NULL,
1350                                  "IoT_TCPReceive", CONFIG_IOTIVITY_TCPRECEIVE_PTHREAD_STACKSIZE);
1351 #endif
1352     if (CA_STATUS_OK != res)
1353     {
1354         oc_mutex_unlock(g_mutexObjectList);
1355         OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
1356         CATCPStopServer();
1357         return res;
1358     }
1359
1360     caglobals.tcp.started = true;
1361     oc_mutex_unlock(g_mutexObjectList);
1362
1363     OIC_LOG(INFO, TAG, "CAReceiveHandler thread started successfully.");
1364     return CA_STATUS_OK;
1365 }
1366
1367 void CATCPStopServer()
1368 {
1369     oc_mutex_lock(g_mutexObjectList);
1370     if (caglobals.tcp.terminate)
1371     {
1372         oc_mutex_unlock(g_mutexObjectList);
1373         OIC_LOG(INFO, TAG, "Adapter is not enabled");
1374         return;
1375     }
1376
1377     // set terminate flag.
1378     caglobals.tcp.terminate = true;
1379
1380     oc_mutex_lock(g_mutexSend);
1381     oc_cond_signal(g_condSend);
1382     oc_mutex_unlock(g_mutexSend);
1383
1384 #ifdef __TIZENRT__
1385     if (caglobals.tcp.started)
1386     {
1387         oc_cond_wait(g_condObjectList, g_mutexObjectList);
1388         caglobals.tcp.started = false;
1389     }
1390 #endif
1391
1392     // close accept socket.
1393 #ifndef __WITH_TLS__
1394     CLOSE_SOCKET(ipv4);
1395     CLOSE_SOCKET(ipv6);
1396 #else
1397     CLOSE_SOCKET(ipv4s);
1398     CLOSE_SOCKET(ipv6s);
1399 #endif
1400
1401     if (caglobals.tcp.connectionFds[1] != OC_INVALID_SOCKET)
1402     {
1403         close(caglobals.tcp.connectionFds[1]);
1404         caglobals.tcp.connectionFds[1] = OC_INVALID_SOCKET;
1405     }
1406     if (caglobals.tcp.connectionFds[0] != OC_INVALID_SOCKET)
1407     {
1408         close(caglobals.tcp.connectionFds[0]);
1409         caglobals.tcp.connectionFds[0] = OC_INVALID_SOCKET;
1410     }
1411 #ifndef __TIZENRT__
1412     if (caglobals.tcp.shutdownFds[1] != OC_INVALID_SOCKET)
1413     {
1414         close(caglobals.tcp.shutdownFds[1]);
1415         caglobals.tcp.shutdownFds[1] = OC_INVALID_SOCKET;
1416         // receive thread will stop immediately
1417     }
1418     if (caglobals.tcp.started)
1419     {
1420         oc_cond_wait(g_condObjectList, g_mutexObjectList);
1421         caglobals.tcp.started = false;
1422     }
1423     if (caglobals.tcp.shutdownFds[0] != OC_INVALID_SOCKET)
1424     {
1425         close(caglobals.tcp.shutdownFds[0]);
1426         caglobals.tcp.shutdownFds[0] = OC_INVALID_SOCKET;
1427     }
1428 #endif
1429     oc_mutex_unlock(g_mutexObjectList);
1430
1431 #ifndef __TIZENRT__
1432     ca_thread_pool_remove_task(g_threadPool, g_taskId);
1433 #endif
1434
1435     CATCPDisconnectAll();
1436     sleep(1);
1437     OIC_LOG(INFO, TAG, "Adapter terminated successfully");
1438 }
1439
1440 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
1441 {
1442     g_packetReceivedCallback = callback;
1443 }
1444
1445 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
1446 {
1447     g_connectionCallback = connHandler;
1448 }
1449
1450 size_t CACheckPayloadLengthFromHeader(const void *data, size_t dlen)
1451 {
1452     VERIFY_NON_NULL_RET(data, TAG, "data", -1);
1453
1454     coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1455             ((unsigned char *)data)[0] >> 4);
1456
1457     coap_pdu_t *pdu = coap_new_pdu2(transport, dlen);
1458     if (!pdu)
1459     {
1460         OIC_LOG(ERROR, TAG, "outpdu is null");
1461         OIC_LOG_V(ERROR, TAG, "data length: %zu", dlen);
1462         return 0;
1463     }
1464
1465     int ret = coap_pdu_parse2((unsigned char *) data, dlen, pdu, transport);
1466     if (0 >= ret)
1467     {
1468         OIC_LOG(ERROR, TAG, "pdu parse failed");
1469         coap_delete_pdu(pdu);
1470         return 0;
1471     }
1472
1473     size_t payloadLen = 0;
1474     size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
1475     OIC_LOG_V(DEBUG, TAG, "headerSize : %zu, pdu length : %d",
1476               headerSize, pdu->length);
1477     if (pdu->length > headerSize)
1478     {
1479         payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
1480     }
1481
1482     OICFree(pdu);
1483
1484     return payloadLen;
1485 }
1486
1487 static ssize_t sendData(const CAEndpoint_t *endpoint, const void *data,
1488                         size_t dlen, const char *fam)
1489 {
1490     OIC_LOG_V(INFO, TAG, "The length of data that needs to be sent is %zu bytes", dlen);
1491
1492     // #1. find a session info from list.
1493     CASocketFd_t sockFd = CAGetSocketFDFromEndpoint(endpoint);
1494     if (OC_INVALID_SOCKET == sockFd)
1495     {
1496         // if there is no connection info, connect to remote device.
1497         sockFd = CAConnectTCPSession(endpoint);
1498         if (OC_INVALID_SOCKET == sockFd)
1499         {
1500             OIC_LOG(ERROR, TAG, "Failed to create tcp session object");
1501             return -1;
1502         }
1503     }
1504
1505     // #2. send data to remote device.
1506     ssize_t remainLen = dlen;
1507     unsigned int sendRetryTime = 1;
1508     do
1509     {
1510 #ifdef MSG_NOSIGNAL
1511         ssize_t len = send(sockFd, data, remainLen, MSG_DONTWAIT | MSG_NOSIGNAL);
1512 #else
1513         ssize_t len = send(sockFd, data, remainLen, MSG_DONTWAIT);
1514 #endif
1515         if (-1 == len)
1516         {
1517             g_lastErrorCode = errno;
1518             OIC_LOG_V(DEBUG, TAG, "Set g_lastErrorCode to %s", strerror(g_lastErrorCode));
1519             if (EWOULDBLOCK != g_lastErrorCode && EAGAIN != g_lastErrorCode)
1520             {
1521                 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(g_lastErrorCode));
1522                 CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
1523                                    len, false, strerror(g_lastErrorCode));
1524                 return len;
1525             }
1526
1527             // re-trying send after 10, 20, 40, 80, 160 and 320 milliseconds
1528             if (sendRetryTime > 32)
1529             {
1530                 return len;
1531             }
1532
1533             unsigned int waitTime = sendRetryTime * 10 * MILLISECONDS_PER_SECOND;
1534             OIC_LOG_V(WARNING, TAG, "send blocked. trying send after %u microseconds", waitTime);
1535
1536             oc_mutex_lock(g_mutexSend);
1537             oc_cond_wait_for(g_condSend, g_mutexSend, waitTime);
1538             oc_mutex_unlock(g_mutexSend);
1539
1540             oc_mutex_lock(g_mutexObjectList);
1541             if (caglobals.tcp.terminate)
1542             {
1543                 oc_mutex_unlock(g_mutexObjectList);
1544                 return len;
1545             }
1546             oc_mutex_unlock(g_mutexObjectList);
1547
1548             sendRetryTime = (sendRetryTime << 1);
1549
1550             continue;
1551         }
1552         sendRetryTime = 1;
1553         data += len;
1554         remainLen -= len;
1555     } while (remainLen > 0);
1556
1557 #ifndef TB_LOG
1558     (void)fam;
1559 #endif
1560     OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
1561     CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
1562                        dlen, true, NULL);
1563     return dlen;
1564 }
1565
1566 ssize_t CATCPSendData(CAEndpoint_t *endpoint, const void *data, size_t datalen)
1567 {
1568     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", -1);
1569     VERIFY_NON_NULL_RET(data, TAG, "data is NULL", -1);
1570
1571     if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
1572     {
1573         return sendData(endpoint, data, datalen, "ipv6");
1574     }
1575     if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
1576     {
1577         return sendData(endpoint, data, datalen, "ipv4");
1578     }
1579
1580     OIC_LOG(ERROR, TAG, "Not supported transport flags");
1581     return -1;
1582 }
1583
1584 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1585 {
1586     VERIFY_NON_NULL(info, TAG, "info is NULL");
1587     VERIFY_NON_NULL(size, TAG, "size is NULL");
1588
1589     return CA_NOT_SUPPORTED;
1590 }
1591
1592 CASocketFd_t CAConnectTCPSession(const CAEndpoint_t *endpoint)
1593 {
1594     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1595
1596     // #1. create TCP server object
1597     CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
1598     if (!svritem)
1599     {
1600         OIC_LOG(ERROR, TAG, "Out of memory");
1601         return OC_INVALID_SOCKET;
1602     }
1603     memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
1604     svritem->sep.endpoint.adapter = endpoint->adapter;
1605     svritem->sep.endpoint.port = endpoint->port;
1606     svritem->sep.endpoint.flags = endpoint->flags;
1607     svritem->sep.endpoint.ifindex = endpoint->ifindex;
1608     svritem->state = CONNECTING;
1609     svritem->isClient = true;
1610
1611     // Allocate message buffer
1612     svritem->tlsdata = (unsigned char*) OICCalloc(TLS_DATA_MAX_SIZE, sizeof(unsigned char));
1613     if (!svritem->tlsdata)
1614     {
1615         OIC_LOG(ERROR, TAG, "Out of memory");
1616         OICFree(svritem);
1617         return OC_INVALID_SOCKET;
1618     }
1619
1620     // #2. add TCP connection info to list
1621     oc_mutex_lock(g_mutexObjectList);
1622     if (caglobals.tcp.svrlist)
1623     {
1624         bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
1625         if (!res)
1626         {
1627             OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
1628             close(svritem->fd);
1629             OICFree(svritem->tlsdata);
1630             OICFree(svritem);
1631             oc_mutex_unlock(g_mutexObjectList);
1632             return OC_INVALID_SOCKET;
1633         }
1634     }
1635     oc_mutex_unlock(g_mutexObjectList);
1636
1637     // #3. create the socket and connect to TCP server
1638     int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
1639     if (CA_STATUS_OK != CATCPCreateSocket(family, svritem))
1640     {
1641         return OC_INVALID_SOCKET;
1642     }
1643
1644     // #4. pass the connection information to CA Common Layer.
1645     if (g_connectionCallback)
1646     {
1647         g_connectionCallback(&(svritem->sep.endpoint), true, svritem->isClient);
1648     }
1649
1650     return svritem->fd;
1651 }
1652
1653 CAResult_t CADisconnectTCPSession(size_t index)
1654 {
1655     CATCPSessionInfo_t *removedData = u_arraylist_remove(caglobals.tcp.svrlist, index);
1656     if (!removedData)
1657     {
1658         OIC_LOG(DEBUG, TAG, "there is no data to be removed");
1659         return CA_STATUS_OK;
1660     }
1661
1662     // close the socket and remove session info in list.
1663     if (removedData->fd >= 0)
1664     {
1665         shutdown(removedData->fd, SHUT_RDWR);
1666         close(removedData->fd);
1667         removedData->fd = -1;
1668         removedData->state = (CONNECTED == removedData->state) ?
1669                                     DISCONNECTED : removedData->state;
1670
1671         // pass the connection information to CA Common Layer.
1672         if (g_connectionCallback && DISCONNECTED == removedData->state)
1673         {
1674             g_connectionCallback(&(removedData->sep.endpoint), false, removedData->isClient);
1675         }
1676     }
1677     OICFree(removedData->data);
1678     removedData->data = NULL;
1679
1680     OICFree(removedData->tlsdata);
1681     removedData->tlsdata = NULL;
1682
1683     OICFree(removedData);
1684     removedData = NULL;
1685
1686     OIC_LOG(DEBUG, TAG, "data is removed from session list");
1687
1688 #ifndef DISABLE_TCP_SERVER
1689     if (caglobals.server && MAX_CONNECTION_COUNTS == u_arraylist_length(caglobals.tcp.svrlist) + 1)
1690     {
1691         CATCPInitializeSocket();
1692     }
1693 #endif
1694
1695     return CA_STATUS_OK;
1696 }
1697
1698 void CATCPDisconnectAll()
1699 {
1700     OIC_LOG(DEBUG, TAG, "IN - CATCPDisconnectAll");
1701
1702     oc_mutex_lock(g_mutexObjectList);
1703
1704     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1705     for (ssize_t index = length; index > 0; index--)
1706     {
1707         // disconnect session from remote device.
1708         CADisconnectTCPSession(index - 1);
1709     }
1710
1711     u_arraylist_destroy(caglobals.tcp.svrlist);
1712     caglobals.tcp.svrlist = NULL;
1713
1714     oc_mutex_unlock(g_mutexObjectList);
1715
1716 #ifdef __WITH_TLS__
1717     CAcloseSslConnectionAll(CA_ADAPTER_TCP);
1718 #endif
1719
1720     OIC_LOG(DEBUG, TAG, "OUT - CATCPDisconnectAll");
1721 }
1722
1723 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
1724 {
1725     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1726     VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
1727
1728     OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1729
1730     // get connection info from list
1731     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1732     for (size_t i = 0; i < length; i++)
1733     {
1734         CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1735                 caglobals.tcp.svrlist, i);
1736         if (!svritem)
1737         {
1738             continue;
1739         }
1740
1741         if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1742                      sizeof(svritem->sep.endpoint.addr))
1743                 && (svritem->sep.endpoint.port == endpoint->port)
1744                 && (svritem->sep.endpoint.flags & endpoint->flags))
1745         {
1746             OIC_LOG(DEBUG, TAG, "Found in session list");
1747             *index = i;
1748             return svritem;
1749         }
1750     }
1751
1752     OIC_LOG(DEBUG, TAG, "Session not found");
1753     return NULL;
1754 }
1755
1756 CASocketFd_t CAGetSocketFDFromEndpoint(const CAEndpoint_t *endpoint)
1757 {
1758     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1759
1760     OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1761
1762     // get connection info from list.
1763     oc_mutex_lock(g_mutexObjectList);
1764     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1765     for (size_t i = 0; i < length; i++)
1766     {
1767         CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1768                 caglobals.tcp.svrlist, i);
1769         if (!svritem)
1770         {
1771             continue;
1772         }
1773
1774         if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1775                      sizeof(svritem->sep.endpoint.addr))
1776                 && (svritem->sep.endpoint.port == endpoint->port)
1777                 && (svritem->sep.endpoint.flags & endpoint->flags))
1778         {
1779             oc_mutex_unlock(g_mutexObjectList);
1780             OIC_LOG(DEBUG, TAG, "Found in session list");
1781             return svritem->fd;
1782         }
1783     }
1784
1785     oc_mutex_unlock(g_mutexObjectList);
1786     OIC_LOG(DEBUG, TAG, "Session not found");
1787     return OC_INVALID_SOCKET;
1788 }
1789
1790 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1791 {
1792
1793     // check from the last item.
1794     CATCPSessionInfo_t *svritem = NULL;
1795     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1796     for (size_t i = 0; i < length; i++)
1797     {
1798         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1799
1800         if (svritem && svritem->fd == fd)
1801         {
1802             *index = i;
1803             oc_mutex_unlock(g_mutexObjectList);
1804             return svritem;
1805         }
1806     }
1807
1808
1809     return NULL;
1810 }
1811
1812 static CATCPSessionInfo_t *CAGetSessionInfoFromFDAsOwner(int fd, size_t *index)
1813 {
1814     CATCPSessionInfo_t *svritem = NULL;
1815     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1816     for (size_t i = 0; i < length; i++)
1817     {
1818         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1819
1820         if (svritem && svritem->fd == fd)
1821         {
1822             *index = i;
1823             return svritem;
1824         }
1825     }
1826
1827     return NULL;
1828 }
1829
1830 CAResult_t CASearchAndDeleteTCPSession(const CAEndpoint_t *endpoint)
1831 {
1832     oc_mutex_lock(g_mutexObjectList);
1833
1834     CAResult_t result = CA_STATUS_OK;
1835     size_t index = 0;
1836     CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1837     if (svritem)
1838     {
1839         result = CADisconnectTCPSession(index);
1840         if (CA_STATUS_OK != result)
1841         {
1842             OIC_LOG_V(ERROR, TAG, "CADisconnectTCPSession failed, result[%d]", result);
1843         }
1844     }
1845
1846     oc_mutex_unlock(g_mutexObjectList);
1847     return result;
1848 }
1849
1850 void CATCPCloseInProgressConnections()
1851 {
1852     OIC_LOG(INFO, TAG, "IN - CATCPCloseInProgressConnections");
1853
1854     oc_mutex_lock(g_mutexObjectList);
1855
1856     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1857     for (size_t index = 0; index < length; index++)
1858     {
1859         CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1860                 caglobals.tcp.svrlist, index);
1861         if (!svritem)
1862         {
1863             continue;
1864         }
1865
1866         // Session which are connecting state
1867         if (svritem->fd >= 0 && svritem->state == CONNECTING)
1868         {
1869             shutdown(svritem->fd, SHUT_RDWR);
1870             close(svritem->fd);
1871             svritem->fd = -1;
1872             svritem->state = DISCONNECTED;
1873         }
1874     }
1875
1876     oc_mutex_unlock(g_mutexObjectList);
1877
1878     OIC_LOG(INFO, TAG, "OUT - CATCPCloseInProgressConnections");
1879 }
1880
1881 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1882 {
1883     OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1884
1885     coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1886             ((unsigned char *)recvBuffer)[0] >> 4);
1887     size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1888                                                         transport);
1889     size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1890
1891     OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%zu]", optPaylaodLen);
1892     OIC_LOG_V(DEBUG, TAG, "header length [%zu]", headerLen);
1893     OIC_LOG_V(DEBUG, TAG, "total data length [%zu]", headerLen + optPaylaodLen);
1894
1895     OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1896     return headerLen + optPaylaodLen;
1897 }
1898
1899 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1900 {
1901     g_tcpErrorHandler = errorHandleCallback;
1902 }
1903
1904 CAResult_t CASetKeepAlive(const CAEndpoint_t *endpoint, int time, int cnt, int intvl)
1905 {
1906     OIC_LOG(INFO, TAG, "IN - CATCPSetKeepAlive");
1907
1908     VERIFY_NON_NULL(endpoint, TAG, "endpoint is NULL");
1909
1910     size_t index = 0;
1911     bool revertKeepAliveSetting = false;
1912     CAResult_t result = CA_STATUS_OK;
1913     oc_mutex_lock(g_mutexObjectList);
1914     CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1915     if (!svritem)
1916     {
1917         // There is no connection with the given endpoint, so the parameter is considered to be invalid.
1918         result = CA_STATUS_INVALID_PARAM;
1919         goto exit;
1920     }
1921
1922     if (svritem->fd < 0 || svritem->state != CONNECTED)
1923     {
1924         result = CA_DESTINATION_DISCONNECTED;
1925         goto exit;
1926     }
1927
1928     int option = 1;
1929     if (-1 == setsockopt(svritem->fd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option)))
1930     {
1931         OIC_LOG_V(ERROR, TAG, "setsockopt SO_KEEPALIVE failed on socket(%d): %s",
1932             svritem->fd, strerror(errno));
1933         result = CA_SOCKET_OPERATION_FAILED;
1934         goto exit;
1935     }
1936
1937     if (-1 == setsockopt(svritem->fd, SOL_TCP, TCP_KEEPIDLE, &time, sizeof(time)))
1938     {
1939         OIC_LOG_V(ERROR, TAG, "setsockopt TCP_KEEPIDLE failed on socket(%d): %s",
1940             svritem->fd, strerror(errno));
1941         revertKeepAliveSetting = true;
1942         result = CA_SOCKET_OPERATION_FAILED;
1943         goto exit;
1944     }
1945
1946     if (-1 == setsockopt(svritem->fd, SOL_TCP, TCP_KEEPCNT, &cnt, sizeof(cnt)))
1947     {
1948         OIC_LOG_V(ERROR, TAG, "setsockopt TCP_KEEPCNT failed on socket(%d): %s",
1949             svritem->fd, strerror(errno));
1950         revertKeepAliveSetting = true;
1951         result = CA_SOCKET_OPERATION_FAILED;
1952         goto exit;
1953     }
1954
1955     if (-1 == setsockopt(svritem->fd, SOL_TCP, TCP_KEEPINTVL, &intvl, sizeof(intvl)))
1956     {
1957         OIC_LOG_V(ERROR, TAG, "setsockopt TCP_KEEPINTVL failed on socket(%d): %s",
1958             svritem->fd, strerror(errno));
1959         revertKeepAliveSetting = true;
1960         result = CA_SOCKET_OPERATION_FAILED;
1961     }
1962
1963 exit:
1964     if (revertKeepAliveSetting)
1965     {
1966         // Unset SO_KEEPALIVE
1967         option = 0;
1968         if (-1 == setsockopt(svritem->fd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option)))
1969         {
1970             OIC_LOG_V(ERROR, TAG, "unset SO_KEEPALIVE failed on socket(%d): %s",
1971                 svritem->fd, strerror(errno));
1972         }
1973     }
1974     oc_mutex_unlock(g_mutexObjectList);
1975     OIC_LOG(INFO, TAG, "OUT - CATCPSetKeepAlive");
1976     return result;
1977 }
1978
1979 CAResult_t CAUnSetKeepAlive(const CAEndpoint_t *endpoint)
1980 {
1981     OIC_LOG(INFO, TAG, "IN - CATCPUnSetKeepAlive");
1982
1983     VERIFY_NON_NULL(endpoint, TAG, "endpoint is NULL");
1984
1985     size_t index = 0;
1986     CAResult_t result = CA_STATUS_OK;
1987     oc_mutex_lock(g_mutexObjectList);
1988     CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1989     if (!svritem)
1990     {
1991         // There is no connection with the given endpoint, so the parameter is considered to be invalid.
1992         result = CA_STATUS_INVALID_PARAM;
1993         goto exit;
1994     }
1995
1996     if (svritem->fd < 0 || svritem->state != CONNECTED)
1997     {
1998         result = CA_DESTINATION_DISCONNECTED;
1999         goto exit;
2000     }
2001
2002     int option = 0;
2003     if (-1 == setsockopt(svritem->fd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option)))
2004     {
2005         OIC_LOG_V(ERROR, TAG, "setsockopt SO_KEEPALIVE failed on socket(%d): %s",
2006             svritem->fd, strerror(errno));
2007         result = CA_SOCKET_OPERATION_FAILED;
2008     }
2009
2010 exit:
2011     oc_mutex_unlock(g_mutexObjectList);
2012     OIC_LOG(INFO, TAG, "OUT - CATCPUnSetKeepAlive");
2013     return result;
2014 }
2015
2016 int CAGetLastErrorCode()
2017 {
2018     return g_lastErrorCode;
2019 }