Update snapshot(2018-02-07)
[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 #define NEWSOCKET(FAMILY, NAME) \
1023     caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
1024     if (caglobals.tcp.NAME.fd == -1) \
1025     { \
1026         caglobals.tcp.NAME.port = 0; \
1027         caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
1028     } \
1029     CHECKFD(caglobals.tcp.NAME.fd);
1030
1031 void CATCPInitializeSocket()
1032 {
1033 #ifndef __WITH_TLS__
1034         NEWSOCKET(AF_INET, ipv4);
1035 #else
1036         NEWSOCKET(AF_INET, ipv4s);
1037 #endif
1038
1039 //TODO Enable once TizenRT supports IPv6
1040 #ifndef __TIZENRT__
1041 #ifndef __WITH_TLS__
1042         NEWSOCKET(AF_INET6, ipv6);
1043 #else
1044         NEWSOCKET(AF_INET6, ipv6s);
1045 #endif
1046 #endif
1047 #ifndef __WITH_TLS__
1048         OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
1049                   caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
1050         OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
1051                   caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
1052 #else
1053         OIC_LOG_V(DEBUG, TAG, "IPv4 secure socket fd=%d, port=%d",
1054                   caglobals.tcp.ipv4s.fd, caglobals.tcp.ipv4s.port);
1055         OIC_LOG_V(DEBUG, TAG, "IPv6 secure socket fd=%d, port=%d",
1056                   caglobals.tcp.ipv6s.fd, caglobals.tcp.ipv6s.port);
1057 #endif
1058 }
1059
1060 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
1061 {
1062     oc_mutex_lock(g_mutexObjectList);
1063     if (caglobals.tcp.started)
1064     {
1065         oc_mutex_unlock(g_mutexObjectList);
1066         OIC_LOG(INFO, TAG, "Adapter is started already");
1067         return CA_STATUS_OK;
1068     }
1069
1070     g_threadPool = threadPool;
1071
1072     if (!caglobals.tcp.ipv4tcpenabled)
1073     {
1074         caglobals.tcp.ipv4tcpenabled = true;    // only needed to run CA tests
1075     }
1076     if (!caglobals.tcp.ipv6tcpenabled)
1077     {
1078         caglobals.tcp.ipv6tcpenabled = true;    // only needed to run CA tests
1079     }
1080
1081     caglobals.tcp.terminate = false;
1082     if (!caglobals.tcp.svrlist)
1083     {
1084         caglobals.tcp.svrlist = u_arraylist_create();
1085     }
1086
1087     if (caglobals.server)
1088     {
1089         CATCPInitializeSocket();
1090     }
1091 #ifndef __TIZENRT__
1092     // create pipe for fast shutdown
1093     CAInitializePipe(caglobals.tcp.shutdownFds);
1094     CHECKFD(caglobals.tcp.shutdownFds[0]);
1095     CHECKFD(caglobals.tcp.shutdownFds[1]);
1096 #endif
1097     // create pipe for connection event
1098     CAInitializePipe(caglobals.tcp.connectionFds);
1099     CHECKFD(caglobals.tcp.connectionFds[0]);
1100     CHECKFD(caglobals.tcp.connectionFds[1]);
1101
1102     CAResult_t res = CA_STATUS_OK;
1103 #ifndef __TIZENRT__
1104     res = ca_thread_pool_add_task(g_threadPool, CAReceiveHandler, NULL, NULL);
1105 #else
1106     res = ca_thread_pool_add_task(g_threadPool, CAReceiveHandler, NULL, NULL,
1107                                  "IoT_TCPReceive", CONFIG_IOTIVITY_TCPRECEIVE_PTHREAD_STACKSIZE);
1108 #endif
1109     if (CA_STATUS_OK != res)
1110     {
1111         oc_mutex_unlock(g_mutexObjectList);
1112         OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
1113         CATCPStopServer();
1114         return res;
1115     }
1116
1117     caglobals.tcp.started = true;
1118     oc_mutex_unlock(g_mutexObjectList);
1119
1120     OIC_LOG(INFO, TAG, "CAReceiveHandler thread started successfully.");
1121     return CA_STATUS_OK;
1122 }
1123
1124 void CATCPStopServer()
1125 {
1126     oc_mutex_lock(g_mutexObjectList);
1127     if (caglobals.tcp.terminate)
1128     {
1129         oc_mutex_unlock(g_mutexObjectList);
1130         OIC_LOG(INFO, TAG, "Adapter is not enabled");
1131         return;
1132     }
1133
1134     // set terminate flag.
1135     caglobals.tcp.terminate = true;
1136
1137     oc_mutex_lock(g_mutexSend);
1138     oc_cond_signal(g_condSend);
1139     oc_mutex_unlock(g_mutexSend);
1140
1141 #ifdef __TIZENRT__
1142     if (caglobals.tcp.started)
1143     {
1144         oc_cond_wait(g_condObjectList, g_mutexObjectList);
1145         caglobals.tcp.started = false;
1146     }
1147 #endif
1148
1149     // close accept socket.
1150 #ifndef __WITH_TLS__
1151     CLOSE_SOCKET(ipv4);
1152     CLOSE_SOCKET(ipv6);
1153 #else
1154     CLOSE_SOCKET(ipv4s);
1155     CLOSE_SOCKET(ipv6s);
1156 #endif
1157
1158     close(caglobals.tcp.connectionFds[1]);
1159     close(caglobals.tcp.connectionFds[0]);
1160     caglobals.tcp.connectionFds[1] = OC_INVALID_SOCKET;
1161     caglobals.tcp.connectionFds[0] = OC_INVALID_SOCKET;
1162 #ifndef __TIZENRT__
1163     if (caglobals.tcp.shutdownFds[1] != OC_INVALID_SOCKET)
1164     {
1165         close(caglobals.tcp.shutdownFds[1]);
1166         caglobals.tcp.shutdownFds[1] = OC_INVALID_SOCKET;
1167         // receive thread will stop immediately
1168     }
1169     if (caglobals.tcp.started)
1170     {
1171         oc_cond_wait(g_condObjectList, g_mutexObjectList);
1172         caglobals.tcp.started = false;
1173     }
1174     if (caglobals.tcp.shutdownFds[0] != OC_INVALID_SOCKET)
1175     {
1176         close(caglobals.tcp.shutdownFds[0]);
1177         caglobals.tcp.shutdownFds[0] = OC_INVALID_SOCKET;
1178     }
1179 #endif
1180     oc_mutex_unlock(g_mutexObjectList);
1181
1182     CATCPDisconnectAll();
1183     sleep(1);
1184
1185     OIC_LOG(INFO, TAG, "Adapter terminated successfully");
1186 }
1187
1188 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
1189 {
1190     g_packetReceivedCallback = callback;
1191 }
1192
1193 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
1194 {
1195     g_connectionCallback = connHandler;
1196 }
1197
1198 size_t CACheckPayloadLengthFromHeader(const void *data, size_t dlen)
1199 {
1200     VERIFY_NON_NULL_RET(data, TAG, "data", -1);
1201
1202     coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1203             ((unsigned char *)data)[0] >> 4);
1204
1205     coap_pdu_t *pdu = coap_new_pdu2(transport, dlen);
1206     if (!pdu)
1207     {
1208         OIC_LOG(ERROR, TAG, "outpdu is null");
1209         OIC_LOG_V(ERROR, TAG, "data length: %zu", dlen);
1210         return 0;
1211     }
1212
1213     int ret = coap_pdu_parse2((unsigned char *) data, dlen, pdu, transport);
1214     if (0 >= ret)
1215     {
1216         OIC_LOG(ERROR, TAG, "pdu parse failed");
1217         coap_delete_pdu(pdu);
1218         return 0;
1219     }
1220
1221     size_t payloadLen = 0;
1222     size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
1223     OIC_LOG_V(DEBUG, TAG, "headerSize : %zu, pdu length : %d",
1224               headerSize, pdu->length);
1225     if (pdu->length > headerSize)
1226     {
1227         payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
1228     }
1229
1230     OICFree(pdu);
1231
1232     return payloadLen;
1233 }
1234
1235 static ssize_t sendData(const CAEndpoint_t *endpoint, const void *data,
1236                         size_t dlen, const char *fam)
1237 {
1238     OIC_LOG_V(INFO, TAG, "The length of data that needs to be sent is %zu bytes", dlen);
1239
1240     // #1. find a session info from list.
1241     CASocketFd_t sockFd = CAGetSocketFDFromEndpoint(endpoint);
1242     if (OC_INVALID_SOCKET == sockFd)
1243     {
1244         // if there is no connection info, connect to remote device.
1245         sockFd = CAConnectTCPSession(endpoint);
1246         if (OC_INVALID_SOCKET == sockFd)
1247         {
1248             OIC_LOG(ERROR, TAG, "Failed to create tcp session object");
1249             return -1;
1250         }
1251     }
1252
1253     // #2. send data to remote device.
1254     ssize_t remainLen = dlen;
1255     unsigned int sendRetryTime = 1;
1256     do
1257     {
1258 #ifdef MSG_NOSIGNAL
1259         ssize_t len = send(sockFd, data, remainLen, MSG_DONTWAIT | MSG_NOSIGNAL);
1260 #else
1261         ssize_t len = send(sockFd, data, remainLen, MSG_DONTWAIT);
1262 #endif
1263         if (-1 == len)
1264         {
1265             if (EWOULDBLOCK != errno && EAGAIN != errno)
1266             {
1267                 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
1268                 CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
1269                                    len, false, strerror(errno));
1270                 return len;
1271             }
1272
1273             // re-trying send after 10, 20, 40, 80, 160 and 320 milliseconds
1274             if (sendRetryTime > 32)
1275             {
1276                 return len;
1277             }
1278
1279             unsigned int waitTime = sendRetryTime * 10 * MILLISECONDS_PER_SECOND;
1280             OIC_LOG_V(WARNING, TAG, "send blocked. trying send after %u microseconds", waitTime);
1281
1282             oc_mutex_lock(g_mutexSend);
1283             oc_cond_wait_for(g_condSend, g_mutexSend, waitTime);
1284             oc_mutex_unlock(g_mutexSend);
1285
1286             if (caglobals.tcp.terminate)
1287             {
1288                 return len;
1289             }
1290
1291             sendRetryTime = (sendRetryTime << 1);
1292
1293             continue;
1294         }
1295         sendRetryTime = 1;
1296         data += len;
1297         remainLen -= len;
1298     } while (remainLen > 0);
1299
1300 #ifndef TB_LOG
1301     (void)fam;
1302 #endif
1303     OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
1304     CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
1305                        dlen, true, NULL);
1306     return dlen;
1307 }
1308
1309 ssize_t CATCPSendData(CAEndpoint_t *endpoint, const void *data, size_t datalen)
1310 {
1311     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", -1);
1312     VERIFY_NON_NULL_RET(data, TAG, "data is NULL", -1);
1313
1314     if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
1315     {
1316         return sendData(endpoint, data, datalen, "ipv6");
1317     }
1318     if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
1319     {
1320         return sendData(endpoint, data, datalen, "ipv4");
1321     }
1322
1323     OIC_LOG(ERROR, TAG, "Not supported transport flags");
1324     return -1;
1325 }
1326
1327 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1328 {
1329     VERIFY_NON_NULL(info, TAG, "info is NULL");
1330     VERIFY_NON_NULL(size, TAG, "size is NULL");
1331
1332     return CA_NOT_SUPPORTED;
1333 }
1334
1335 CASocketFd_t CAConnectTCPSession(const CAEndpoint_t *endpoint)
1336 {
1337     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1338
1339     // #1. create TCP server object
1340     CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
1341     if (!svritem)
1342     {
1343         OIC_LOG(ERROR, TAG, "Out of memory");
1344         return OC_INVALID_SOCKET;
1345     }
1346     memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
1347     svritem->sep.endpoint.adapter = endpoint->adapter;
1348     svritem->sep.endpoint.port = endpoint->port;
1349     svritem->sep.endpoint.flags = endpoint->flags;
1350     svritem->sep.endpoint.ifindex = endpoint->ifindex;
1351     svritem->state = CONNECTING;
1352     svritem->isClient = true;
1353
1354     // Allocate message buffer
1355     svritem->tlsdata = (unsigned char*) OICCalloc(TLS_DATA_MAX_SIZE, sizeof(unsigned char));
1356     if (!svritem->tlsdata)
1357     {
1358         OIC_LOG(ERROR, TAG, "Out of memory");
1359         OICFree(svritem);
1360         return OC_INVALID_SOCKET;
1361     }
1362
1363     // #2. add TCP connection info to list
1364     oc_mutex_lock(g_mutexObjectList);
1365     if (caglobals.tcp.svrlist)
1366     {
1367         bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
1368         if (!res)
1369         {
1370             OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
1371             close(svritem->fd);
1372             OICFree(svritem->tlsdata);
1373             OICFree(svritem);
1374             oc_mutex_unlock(g_mutexObjectList);
1375             return OC_INVALID_SOCKET;
1376         }
1377     }
1378     oc_mutex_unlock(g_mutexObjectList);
1379
1380     // #3. create the socket and connect to TCP server
1381     int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
1382     if (CA_STATUS_OK != CATCPCreateSocket(family, svritem))
1383     {
1384         return OC_INVALID_SOCKET;
1385     }
1386
1387     // #4. pass the connection information to CA Common Layer.
1388     if (g_connectionCallback)
1389     {
1390         g_connectionCallback(&(svritem->sep.endpoint), true, svritem->isClient);
1391     }
1392
1393     return svritem->fd;
1394 }
1395
1396 CAResult_t CADisconnectTCPSession(size_t index)
1397 {
1398     CATCPSessionInfo_t *removedData = u_arraylist_remove(caglobals.tcp.svrlist, index);
1399     if (!removedData)
1400     {
1401         OIC_LOG(DEBUG, TAG, "there is no data to be removed");
1402         return CA_STATUS_OK;
1403     }
1404
1405     // close the socket and remove session info in list.
1406     if (removedData->fd >= 0)
1407     {
1408         shutdown(removedData->fd, SHUT_RDWR);
1409         close(removedData->fd);
1410         removedData->fd = -1;
1411         removedData->state = (CONNECTED == removedData->state) ?
1412                                     DISCONNECTED : removedData->state;
1413
1414         // pass the connection information to CA Common Layer.
1415         if (g_connectionCallback && DISCONNECTED == removedData->state)
1416         {
1417             g_connectionCallback(&(removedData->sep.endpoint), false, removedData->isClient);
1418         }
1419     }
1420     OICFree(removedData->data);
1421     removedData->data = NULL;
1422
1423     OICFree(removedData->tlsdata);
1424     removedData->tlsdata = NULL;
1425
1426     OICFree(removedData);
1427     removedData = NULL;
1428
1429     OIC_LOG(DEBUG, TAG, "data is removed from session list");
1430
1431     if (caglobals.server && MAX_CONNECTION_COUNTS == u_arraylist_length(caglobals.tcp.svrlist) + 1)
1432     {
1433         CATCPInitializeSocket();
1434     }
1435     return CA_STATUS_OK;
1436 }
1437
1438 void CATCPDisconnectAll()
1439 {
1440     OIC_LOG(DEBUG, TAG, "IN - CATCPDisconnectAll");
1441
1442     oc_mutex_lock(g_mutexObjectList);
1443
1444     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1445     for (ssize_t index = length; index > 0; index--)
1446     {
1447         // disconnect session from remote device.
1448         CADisconnectTCPSession(index - 1);
1449     }
1450
1451     u_arraylist_destroy(caglobals.tcp.svrlist);
1452     caglobals.tcp.svrlist = NULL;
1453
1454     oc_mutex_unlock(g_mutexObjectList);
1455
1456 #ifdef __WITH_TLS__
1457     CAcloseSslConnectionAll(CA_ADAPTER_TCP);
1458 #endif
1459
1460     OIC_LOG(DEBUG, TAG, "OUT - CATCPDisconnectAll");
1461 }
1462
1463 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
1464 {
1465     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1466     VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
1467
1468     OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1469
1470     // get connection info from list
1471     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1472     for (size_t i = 0; i < length; i++)
1473     {
1474         CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1475                 caglobals.tcp.svrlist, i);
1476         if (!svritem)
1477         {
1478             continue;
1479         }
1480
1481         if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1482                      sizeof(svritem->sep.endpoint.addr))
1483                 && (svritem->sep.endpoint.port == endpoint->port)
1484                 && (svritem->sep.endpoint.flags & endpoint->flags))
1485         {
1486             OIC_LOG(DEBUG, TAG, "Found in session list");
1487             *index = i;
1488             return svritem;
1489         }
1490     }
1491
1492     OIC_LOG(DEBUG, TAG, "Session not found");
1493     return NULL;
1494 }
1495
1496 CASocketFd_t CAGetSocketFDFromEndpoint(const CAEndpoint_t *endpoint)
1497 {
1498     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1499
1500     OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1501
1502     // get connection info from list.
1503     oc_mutex_lock(g_mutexObjectList);
1504     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1505     for (size_t i = 0; i < length; i++)
1506     {
1507         CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1508                 caglobals.tcp.svrlist, i);
1509         if (!svritem)
1510         {
1511             continue;
1512         }
1513
1514         if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1515                      sizeof(svritem->sep.endpoint.addr))
1516                 && (svritem->sep.endpoint.port == endpoint->port)
1517                 && (svritem->sep.endpoint.flags & endpoint->flags))
1518         {
1519             oc_mutex_unlock(g_mutexObjectList);
1520             OIC_LOG(DEBUG, TAG, "Found in session list");
1521             return svritem->fd;
1522         }
1523     }
1524
1525     oc_mutex_unlock(g_mutexObjectList);
1526     OIC_LOG(DEBUG, TAG, "Session not found");
1527     return OC_INVALID_SOCKET;
1528 }
1529
1530 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1531 {
1532
1533     // check from the last item.
1534     CATCPSessionInfo_t *svritem = NULL;
1535     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1536     for (size_t i = 0; i < length; i++)
1537     {
1538         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1539
1540         if (svritem && svritem->fd == fd)
1541         {
1542             *index = i;
1543             oc_mutex_unlock(g_mutexObjectList);
1544             return svritem;
1545         }
1546     }
1547
1548
1549     return NULL;
1550 }
1551
1552 static CATCPSessionInfo_t *CAGetSessionInfoFromFDAsOwner(int fd, size_t *index)
1553 {
1554     CATCPSessionInfo_t *svritem = NULL;
1555     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1556     for (size_t i = 0; i < length; i++)
1557     {
1558         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1559
1560         if (svritem && svritem->fd == fd)
1561         {
1562             *index = i;
1563             return svritem;
1564         }
1565     }
1566
1567     return NULL;
1568 }
1569
1570 CAResult_t CASearchAndDeleteTCPSession(const CAEndpoint_t *endpoint)
1571 {
1572     oc_mutex_lock(g_mutexObjectList);
1573
1574     CAResult_t result = CA_STATUS_OK;
1575     size_t index = 0;
1576     CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1577     if (svritem)
1578     {
1579         result = CADisconnectTCPSession(index);
1580         if (CA_STATUS_OK != result)
1581         {
1582             OIC_LOG_V(ERROR, TAG, "CADisconnectTCPSession failed, result[%d]", result);
1583         }
1584     }
1585
1586     oc_mutex_unlock(g_mutexObjectList);
1587     return result;
1588 }
1589
1590 void CATCPCloseInProgressConnections()
1591 {
1592     OIC_LOG(INFO, TAG, "IN - CATCPCloseInProgressConnections");
1593
1594     oc_mutex_lock(g_mutexObjectList);
1595
1596     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1597     for (size_t index = 0; index < length; index++)
1598     {
1599         CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1600                 caglobals.tcp.svrlist, index);
1601         if (!svritem)
1602         {
1603             continue;
1604         }
1605
1606         // Session which are connecting state
1607         if (svritem->fd >= 0 && svritem->state == CONNECTING)
1608         {
1609             shutdown(svritem->fd, SHUT_RDWR);
1610             close(svritem->fd);
1611             svritem->fd = -1;
1612             svritem->state = DISCONNECTED;
1613         }
1614     }
1615
1616     oc_mutex_unlock(g_mutexObjectList);
1617
1618     OIC_LOG(INFO, TAG, "OUT - CATCPCloseInProgressConnections");
1619 }
1620
1621 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1622 {
1623     OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1624
1625     coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1626             ((unsigned char *)recvBuffer)[0] >> 4);
1627     size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1628                                                         transport);
1629     size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1630
1631     OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%zu]", optPaylaodLen);
1632     OIC_LOG_V(DEBUG, TAG, "header length [%zu]", headerLen);
1633     OIC_LOG_V(DEBUG, TAG, "total data length [%zu]", headerLen + optPaylaodLen);
1634
1635     OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1636     return headerLen + optPaylaodLen;
1637 }
1638
1639 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1640 {
1641     g_tcpErrorHandler = errorHandleCallback;
1642 }