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