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