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