Merge branch 'master' into group-manager
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / tcp_adapter / catcpserver.c
1 /* ****************************************************************j
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/ioctl.h>
24 #include <stdio.h>
25 #include <unistd.h>
26 #include <sys/types.h>
27 #include <fcntl.h>
28 #include <sys/select.h>
29 #include <arpa/inet.h>
30 #include <netinet/in.h>
31 #include <net/if.h>
32 #include <errno.h>
33 #include <sys/poll.h>
34
35 #ifndef WITH_ARDUINO
36 #include <sys/socket.h>
37 #include <netinet/in.h>
38 #include <netdb.h>
39 #endif
40
41 #include "catcpinterface.h"
42 #include "pdu.h"
43 #include "caadapterutils.h"
44 #include "camutex.h"
45 #include "oic_malloc.h"
46 #include "oic_string.h"
47
48 /**
49  * Logging tag for module name.
50  */
51 #define TAG "OIC_CA_TCP_SERVER"
52
53 /**
54  * Server port number for local test.
55  */
56 #define SERVER_PORT 8000
57
58 /**
59  * Maximum CoAP over TCP header length
60  * to know the total data length.
61  */
62 #define TCP_MAX_HEADER_LEN  6
63
64 /**
65  * Accept server file descriptor.
66  */
67 static int g_acceptServerFD = -1;
68
69 /**
70  * Mutex to synchronize device object list.
71  */
72 static ca_mutex g_mutexObjectList = NULL;
73
74 /**
75  * Conditional mutex to synchronize.
76  */
77 static ca_cond g_condObjectList = NULL;
78
79 /**
80  * Maintains the callback to be notified when data received from remote device.
81  */
82 static CATCPPacketReceivedCallback g_packetReceivedCallback;
83
84 /**
85  * Error callback to update error in TCP.
86  */
87 static CATCPErrorHandleCallback g_TCPErrorHandler = NULL;
88
89 static CAResult_t CATCPCreateMutex();
90 static void CATCPDestroyMutex();
91 static CAResult_t CATCPCreateCond();
92 static void CATCPDestroyCond();
93 static CAResult_t CACreateAcceptSocket();
94 static void CAAcceptConnection();
95 static void CAFindReadyMessage();
96 static void CASelectReturned(fd_set *readFds, int ret);
97 static void CAReceiveMessage(int fd);
98 static void CAReceiveHandler(void *data);
99 static int CATCPCreateSocket(int family, CATCPSessionInfo_t *tcpServerInfo);
100
101 #define CHECKFD(FD) \
102     if (FD > caglobals.tcp.maxfd) \
103         caglobals.tcp.maxfd = FD;
104
105 static void CATCPDestroyMutex()
106 {
107     if (g_mutexObjectList)
108     {
109         ca_mutex_free(g_mutexObjectList);
110         g_mutexObjectList = NULL;
111     }
112 }
113
114 static CAResult_t CATCPCreateMutex()
115 {
116     if (!g_mutexObjectList)
117     {
118         g_mutexObjectList = ca_mutex_new();
119         if (!g_mutexObjectList)
120         {
121             OIC_LOG(ERROR, TAG, "Failed to created mutex!");
122             return CA_STATUS_FAILED;
123         }
124     }
125
126     return CA_STATUS_OK;
127 }
128
129 static void CATCPDestroyCond()
130 {
131     if (g_condObjectList)
132     {
133         ca_cond_free(g_condObjectList);
134         g_condObjectList = NULL;
135     }
136 }
137
138 static CAResult_t CATCPCreateCond()
139 {
140     if (!g_condObjectList)
141     {
142         g_condObjectList = ca_cond_new();
143         if (!g_condObjectList)
144         {
145             OIC_LOG(ERROR, TAG, "Failed to created cond!");
146             return CA_STATUS_FAILED;
147         }
148     }
149     return CA_STATUS_OK;
150 }
151
152 static void CAReceiveHandler(void *data)
153 {
154     (void)data;
155     OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler");
156
157     while (!caglobals.tcp.terminate)
158     {
159         CAFindReadyMessage();
160     }
161
162     ca_mutex_lock(g_mutexObjectList);
163     ca_cond_signal(g_condObjectList);
164     ca_mutex_unlock(g_mutexObjectList);
165
166     OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
167 }
168
169 static void CAFindReadyMessage()
170 {
171     fd_set readFds;
172     struct timeval timeout = { .tv_sec = caglobals.tcp.selectTimeout };
173
174     FD_ZERO(&readFds);
175
176     if (-1 != g_acceptServerFD)
177     {
178         FD_SET(g_acceptServerFD, &readFds);
179     }
180     if (-1 != caglobals.tcp.shutdownFds[0])
181     {
182         FD_SET(caglobals.tcp.shutdownFds[0], &readFds);
183     }
184
185     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
186     for (size_t i = 0; i < length; i++)
187     {
188         CATCPSessionInfo_t *svritem =
189                 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
190         if (svritem && 0 <= svritem->fd)
191         {
192             FD_SET(svritem->fd, &readFds);
193         }
194     }
195
196     int ret = select(caglobals.tcp.maxfd + 1, &readFds, NULL, NULL, &timeout);
197
198     if (caglobals.tcp.terminate)
199     {
200         OIC_LOG_V(DEBUG, TAG, "Packet receiver Stop request received.");
201         return;
202     }
203     if (0 >= ret)
204     {
205         if (0 > ret)
206         {
207             OIC_LOG_V(FATAL, TAG, "select error %s", strerror(errno));
208         }
209         return;
210     }
211
212     CASelectReturned(&readFds, ret);
213 }
214
215 static void CASelectReturned(fd_set *readFds, int ret)
216 {
217     (void)ret;
218
219     if (g_acceptServerFD != -1 && FD_ISSET(g_acceptServerFD, readFds))
220     {
221         CAAcceptConnection();
222         return;
223     }
224     else
225     {
226         uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
227         for (size_t i = 0; i < length; i++)
228         {
229             CATCPSessionInfo_t *svritem =
230                     (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
231             if (svritem && svritem->fd >= 0)
232             {
233                 if (FD_ISSET(svritem->fd, readFds))
234                 {
235                     CAReceiveMessage(svritem->fd);
236                     FD_CLR(svritem->fd, readFds);
237                 }
238             }
239         }
240     }
241 }
242
243 static void CAAcceptConnection()
244 {
245     struct sockaddr_storage clientaddr;
246     socklen_t clientlen = sizeof (struct sockaddr_in);
247
248     int sockfd = accept(g_acceptServerFD, (struct sockaddr *)&clientaddr,
249                         &clientlen);
250     if (-1 != sockfd)
251     {
252         CATCPSessionInfo_t *svritem =
253                 (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
254         if (!svritem)
255         {
256             OIC_LOG(ERROR, TAG, "Out of memory");
257             close(sockfd);
258             return;
259         }
260
261         svritem->fd = sockfd;
262         CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
263                             (char *) &svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
264
265         ca_mutex_lock(g_mutexObjectList);
266         bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem);
267         if (!result)
268         {
269             OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
270             close(sockfd);
271             OICFree(svritem);
272             ca_mutex_unlock(g_mutexObjectList);
273             return;
274         }
275         ca_mutex_unlock(g_mutexObjectList);
276
277         CHECKFD(sockfd);
278     }
279 }
280
281 static void CAReceiveMessage(int fd)
282 {
283     // #1. get remote device information from file descriptor.
284     size_t index = 0;
285     CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFD(fd, &index);
286     if (!svritem)
287     {
288         OIC_LOG(ERROR, TAG, "there is no connection information in list");
289         return;
290     }
291
292     // #2. get already allocated memory size.
293     size_t bufSize = (svritem->totalDataLen == 0) ? TCP_MAX_HEADER_LEN : svritem->totalDataLen;
294     if (!svritem->recvData)
295     {
296         svritem->recvData = (unsigned char *) OICCalloc(1, bufSize);
297         if (!svritem->recvData)
298         {
299             OIC_LOG(ERROR, TAG, "out of memory");
300             CADisconnectTCPSession(svritem, index);
301             return;
302         }
303     }
304
305     // #3. receive data from remote device.
306     ssize_t recvLen = recv(fd, svritem->recvData + svritem->recvDataLen,
307                            bufSize - svritem->recvDataLen, 0);
308     if (recvLen <= 0)
309     {
310         if(EWOULDBLOCK != errno)
311         {
312             OIC_LOG_V(ERROR, TAG, "Recvfrom failed %s", strerror(errno));
313             CADisconnectTCPSession(svritem, index);
314         }
315         return;
316     }
317     svritem->recvDataLen += recvLen;
318
319     // #4. get actual data length from coap over tcp header.
320     if (!svritem->totalDataLen)
321     {
322         coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
323                 ((unsigned char *) svritem->recvData)[0] >> 4);
324
325         size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
326         if (svritem->recvDataLen >= headerLen)
327         {
328             svritem->totalDataLen = CAGetTotalLengthFromHeader(
329                     (unsigned char *) svritem->recvData);
330             bufSize = svritem->totalDataLen;
331             unsigned char *newBuf = OICRealloc(svritem->recvData, bufSize);
332             if (!newBuf)
333             {
334                 OIC_LOG(ERROR, TAG, "out of memory");
335                 CADisconnectTCPSession(svritem, index);
336                 return;
337             }
338             svritem->recvData = newBuf;
339         }
340     }
341
342     // #5. pass the received data information to upper layer.
343     if ((svritem->totalDataLen == svritem->recvDataLen) && g_packetReceivedCallback)
344     {
345         svritem->sep.endpoint.adapter = CA_ADAPTER_TCP;
346         g_packetReceivedCallback(&svritem->sep, svritem->recvData, svritem->recvDataLen);
347         OIC_LOG_V(DEBUG, TAG, "total received data len:%d", svritem->recvDataLen);
348
349         // initialize data info to receive next message.
350         OICFree(svritem->recvData);
351         svritem->recvData = NULL;
352         svritem->recvDataLen = 0;
353         svritem->totalDataLen = 0;
354     }
355
356     return;
357 }
358
359 static int CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
360 {
361     // create tcp socket
362     int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
363     if (-1 == fd)
364     {
365         OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
366         goto exit;
367     }
368
369     struct sockaddr_storage sa = { .ss_family = family };
370     CAConvertNameToAddr(svritem->sep.endpoint.addr, svritem->sep.endpoint.port, &sa);
371     socklen_t socklen = sizeof (struct sockaddr_in);
372
373     // connect to TCP server
374     int ret = connect(fd, (struct sockaddr *)&sa, socklen);
375     if (0 == ret)
376     {
377         OIC_LOG(DEBUG, TAG, "connect socket success");
378     }
379     else if (EINPROGRESS == errno)
380     {
381         OIC_LOG(DEBUG, TAG, "EINPROGRESS");
382         int error = 0;
383         socklen_t len = sizeof(error);
384         if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &len) < 0)
385         {
386             OIC_LOG(ERROR, TAG, "getsockopt() error");
387             goto exit;
388         }
389
390         if (error)
391         {
392             if (ECONNREFUSED == error)
393             {
394                 OIC_LOG(ERROR, TAG, "connection refused");
395                 goto exit;
396             }
397             OIC_LOG(ERROR, TAG, "failed to connect socket");
398             goto exit;
399         }
400         OIC_LOG(DEBUG, TAG, "connect socket success");
401     }
402     else
403     {
404         OIC_LOG(ERROR, TAG, "failed to connect socket");
405         goto exit;
406     }
407
408     return fd;
409
410 exit:
411     if (fd >= 0)
412     {
413         close(fd);
414     }
415     return -1;
416 }
417
418 static CAResult_t CACreateAcceptSocket()
419 {
420     int reuse = 1;
421     struct sockaddr_in server = { .sin_addr.s_addr = INADDR_ANY,
422                                   .sin_family = AF_INET,
423                                   .sin_port = htons(SERVER_PORT),
424                                   .sin_zero = { 0 } };
425
426     g_acceptServerFD = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
427     if (g_acceptServerFD < 0)
428     {
429         OIC_LOG(ERROR, TAG, "Failed to create socket");
430         goto exit;
431     }
432
433     if (-1 == setsockopt(g_acceptServerFD, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
434     {
435         OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
436         goto exit;
437     }
438
439     int serverlen = sizeof(server);
440     if (-1 == bind(g_acceptServerFD, (struct sockaddr *)&server, serverlen))
441     {
442         OIC_LOG(ERROR, TAG, "bind() error");
443         goto exit;
444     }
445
446     if (listen(g_acceptServerFD, caglobals.tcp.listenBacklog) != 0)
447     {
448         OIC_LOG(ERROR, TAG, "listen() error");
449         goto exit;
450     }
451
452     CHECKFD(g_acceptServerFD);
453
454     return CA_STATUS_OK;
455
456 exit:
457     if (g_acceptServerFD >= 0)
458     {
459         close(g_acceptServerFD);
460         g_acceptServerFD = -1;
461     }
462     return CA_STATUS_FAILED;
463 }
464
465 static void CAInitializePipe()
466 {
467     int ret = pipe(caglobals.tcp.shutdownFds);
468     if (-1 != ret)
469     {
470         ret = fcntl(caglobals.tcp.shutdownFds[0], F_GETFD);
471         if (-1 != ret)
472         {
473             ret = fcntl(caglobals.tcp.shutdownFds[0], F_SETFD, ret|FD_CLOEXEC);
474         }
475         if (-1 != ret)
476         {
477             ret = fcntl(caglobals.tcp.shutdownFds[1], F_GETFD);
478         }
479         if (-1 != ret)
480         {
481             ret = fcntl(caglobals.tcp.shutdownFds[1], F_SETFD, ret|FD_CLOEXEC);
482         }
483         if (-1 == ret)
484         {
485             close(caglobals.tcp.shutdownFds[1]);
486             close(caglobals.tcp.shutdownFds[0]);
487
488             caglobals.tcp.shutdownFds[0] = -1;
489             caglobals.tcp.shutdownFds[1] = -1;
490
491             OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
492         }
493     }
494 }
495
496 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
497 {
498     if (caglobals.tcp.started)
499     {
500         return CA_STATUS_OK;
501     }
502
503     if (!caglobals.tcp.ipv4tcpenabled)
504     {
505         caglobals.tcp.ipv4tcpenabled = true;    // only needed to run CA tests
506     }
507
508     CAResult_t res = CATCPCreateMutex();
509     if (CA_STATUS_OK == res)
510     {
511         res = CATCPCreateCond();
512     }
513     if (CA_STATUS_OK != res)
514     {
515         OIC_LOG(ERROR, TAG, "failed to create mutex/cond");
516         return res;
517     }
518
519     ca_mutex_lock(g_mutexObjectList);
520     if (!caglobals.tcp.svrlist)
521     {
522         caglobals.tcp.svrlist = u_arraylist_create();
523     }
524     ca_mutex_unlock(g_mutexObjectList);
525
526     res = CACreateAcceptSocket();
527     if (CA_STATUS_OK != res)
528     {
529         OIC_LOG(ERROR, TAG, "failed to create accept socket");
530         return res;
531     }
532
533     // create pipe for fast shutdown
534     CAInitializePipe();
535     CHECKFD(caglobals.tcp.shutdownFds[0]);
536     CHECKFD(caglobals.tcp.shutdownFds[1]);
537
538     caglobals.tcp.terminate = false;
539     res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
540     if (CA_STATUS_OK != res)
541     {
542         OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
543         return res;
544     }
545     OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
546
547     caglobals.tcp.started = true;
548     return CA_STATUS_OK;
549 }
550
551 void CATCPStopServer()
552 {
553     // mutex lock
554     ca_mutex_lock(g_mutexObjectList);
555
556     // set terminate flag
557     caglobals.tcp.terminate = true;
558
559     if (caglobals.tcp.shutdownFds[1] != -1)
560     {
561         close(caglobals.tcp.shutdownFds[1]);
562         // receive thread will stop immediately
563     }
564
565     if (caglobals.tcp.started)
566     {
567         ca_cond_wait(g_condObjectList, g_mutexObjectList);
568     }
569     caglobals.tcp.started = false;
570
571     // mutex unlock
572     ca_mutex_unlock(g_mutexObjectList);
573
574     if (-1 != g_acceptServerFD)
575     {
576         close(g_acceptServerFD);
577         g_acceptServerFD = -1;
578     }
579
580     CATCPDisconnectAll();
581     CATCPDestroyMutex();
582     CATCPDestroyCond();
583 }
584
585 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
586 {
587     g_packetReceivedCallback = callback;
588 }
589
590 static size_t CACheckPayloadLength(const void *data, size_t dlen)
591 {
592     VERIFY_NON_NULL_RET(data, TAG, "data", -1);
593
594     coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
595             ((unsigned char *)data)[0] >> 4);
596
597     coap_pdu_t *pdu = coap_new_pdu(transport, dlen);
598     if (!pdu)
599     {
600         OIC_LOG(ERROR, TAG, "outpdu is null");
601         return 0;
602     }
603
604     int ret = coap_pdu_parse((unsigned char *) data, dlen, pdu, transport);
605     if (0 >= ret)
606     {
607         OIC_LOG(ERROR, TAG, "pdu parse failed");
608         coap_delete_pdu(pdu);
609         return 0;
610     }
611
612     size_t payloadLen = 0;
613     size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
614     OIC_LOG_V(DEBUG, TAG, "headerSize : %d, pdu length : %d",
615               headerSize, pdu->length);
616     if (pdu->length > headerSize)
617     {
618         payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
619     }
620
621     OICFree(pdu);
622
623     return payloadLen;
624 }
625
626 static void sendData(const CAEndpoint_t *endpoint,
627                      const void *data, size_t dlen)
628 {
629     // #1. get TCP Server object from list
630     size_t index = 0;
631     CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
632     if (!svritem)
633     {
634         // if there is no connection info, connect to TCP Server
635         svritem = CAConnectTCPSession(endpoint);
636         if (!svritem)
637         {
638             OIC_LOG(ERROR, TAG, "Failed to create TCP server object");
639             g_TCPErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
640             return;
641         }
642     }
643
644     // #2. check payload length
645     size_t payloadLen = CACheckPayloadLength(data, dlen);
646     // if payload length is zero, disconnect from TCP server
647     if (!payloadLen)
648     {
649         OIC_LOG(DEBUG, TAG, "payload length is zero, disconnect from remote device");
650         CADisconnectTCPSession(svritem, index);
651         return;
652     }
653
654     // #3. check connection state
655     if (svritem->fd < 0)
656     {
657         // if file descriptor value is wrong, remove TCP Server info from list
658         OIC_LOG(ERROR, TAG, "Failed to connect to TCP server");
659         CADisconnectTCPSession(svritem, index);
660         g_TCPErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
661         return;
662     }
663
664     // #4. send data to TCP Server
665     ssize_t remainLen = dlen;
666     do
667     {
668         ssize_t len = send(svritem->fd, data, remainLen, 0);
669         if (-1 == len)
670         {
671             if (EWOULDBLOCK != errno)
672             {
673                 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
674                 g_TCPErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
675                 return;
676             }
677             continue;
678         }
679         data += len;
680         remainLen -= len;
681     } while (remainLen > 0);
682
683     OIC_LOG_V(INFO, TAG, "unicast ipv4tcp sendTo is successful: %zu bytes", dlen);
684 }
685
686 void CATCPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
687                    bool isMulticast)
688 {
689     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
690     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
691
692     if (!isMulticast)
693     {
694         if (caglobals.tcp.ipv4tcpenabled && (endpoint->adapter & CA_ADAPTER_TCP))
695         {
696             sendData(endpoint, data, datalen);
697         }
698     }
699 }
700
701 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
702 {
703     VERIFY_NON_NULL(info, TAG, "info is NULL");
704     VERIFY_NON_NULL(size, TAG, "size is NULL");
705
706     return CA_NOT_SUPPORTED;
707 }
708
709 CATCPSessionInfo_t *CAConnectTCPSession(const CAEndpoint_t *endpoint)
710 {
711     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
712
713     // #1. create TCP server object
714     CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
715     if (!svritem)
716     {
717         OIC_LOG(ERROR, TAG, "Out of memory");
718         return NULL;
719     }
720     memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
721     svritem->sep.endpoint.port = endpoint->port;
722
723     // #2. create the socket and connect to TCP server
724     if (caglobals.tcp.ipv4tcpenabled)
725     {
726         int fd = CATCPCreateSocket(AF_INET, svritem);
727         if (-1 == fd)
728         {
729             OICFree(svritem);
730             return NULL;
731         }
732
733         // #3. add TCP connection info to list
734         svritem->fd = fd;
735         ca_mutex_lock(g_mutexObjectList);
736         if (caglobals.tcp.svrlist)
737         {
738             bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
739             if (!res)
740             {
741                 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
742                 close(svritem->fd);
743                 OICFree(svritem);
744                 ca_mutex_unlock(g_mutexObjectList);
745                 return NULL;
746             }
747         }
748         ca_mutex_unlock(g_mutexObjectList);
749
750         CHECKFD(fd);
751     }
752
753     return svritem;
754 }
755
756 CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *svritem, size_t index)
757 {
758     VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
759
760     ca_mutex_lock(g_mutexObjectList);
761
762     // close the socket and remove TCP connection info in list
763     if (svritem->fd >= 0)
764     {
765         close(svritem->fd);
766     }
767     u_arraylist_remove(caglobals.tcp.svrlist, index);
768     OICFree(svritem->recvData);
769     OICFree(svritem);
770     ca_mutex_unlock(g_mutexObjectList);
771
772     return CA_STATUS_OK;
773 }
774
775 void CATCPDisconnectAll()
776 {
777     ca_mutex_lock(g_mutexObjectList);
778     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
779
780     CATCPSessionInfo_t *svritem = NULL;
781     for (size_t i = 0; i < length; i++)
782     {
783         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
784         if (svritem && svritem->fd >= 0)
785         {
786             shutdown(svritem->fd, SHUT_RDWR);
787             close(svritem->fd);
788             OICFree(svritem->recvData);
789         }
790     }
791     u_arraylist_destroy(caglobals.tcp.svrlist);
792     ca_mutex_unlock(g_mutexObjectList);
793 }
794
795 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint,
796                                                     size_t *index)
797 {
798     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
799     VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
800
801     // get connection info from list
802     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
803     for (size_t i = 0; i < length; i++)
804     {
805         CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
806                 caglobals.tcp.svrlist, i);
807         if (!svritem)
808         {
809             continue;
810         }
811
812         if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
813                      sizeof(svritem->sep.endpoint.addr))
814                 && (svritem->sep.endpoint.port == endpoint->port))
815         {
816             *index = i;
817             return svritem;
818         }
819     }
820
821     return NULL;
822 }
823
824 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
825 {
826     ca_mutex_lock(g_mutexObjectList);
827
828     // check from the last item.
829     CATCPSessionInfo_t *svritem = NULL;
830     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
831     for (size_t i = 0; i < length; i++)
832     {
833         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
834
835         if (svritem && svritem->fd == fd)
836         {
837             *index = i;
838             ca_mutex_unlock(g_mutexObjectList);
839             return svritem;
840         }
841     }
842
843     ca_mutex_unlock(g_mutexObjectList);
844
845     return NULL;
846 }
847
848 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
849 {
850     OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
851
852     coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
853             ((unsigned char *)recvBuffer)[0] >> 4);
854     size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
855                                                         transport);
856     size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
857
858     OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%d]", optPaylaodLen);
859     OIC_LOG_V(DEBUG, TAG, "header length [%d]", headerLen);
860     OIC_LOG_V(DEBUG, TAG, "total data length [%d]", headerLen + optPaylaodLen);
861
862     OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
863     return headerLen + optPaylaodLen;
864 }
865
866 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
867 {
868     g_TCPErrorHandler = errorHandleCallback;
869 }