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