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