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