changes the tcp adapter logic for exception case.
[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 "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->endpoint.addr, &svritem->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->endpoint.adapter = CA_ADAPTER_TCP;
346         g_packetReceivedCallback(&svritem->endpoint, 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 *tcpServerInfo)
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(tcpServerInfo->endpoint.addr, tcpServerInfo->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
425     g_acceptServerFD = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
426     if (g_acceptServerFD < 0)
427     {
428         OIC_LOG(ERROR, TAG, "Failed to create socket");
429         goto exit;
430     }
431
432     if (-1 == setsockopt(g_acceptServerFD, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
433     {
434         OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
435         goto exit;
436     }
437
438     int serverlen = sizeof(server);
439     if (-1 == bind(g_acceptServerFD, (struct sockaddr *)&server, serverlen))
440     {
441         OIC_LOG(ERROR, TAG, "bind() error");
442         goto exit;
443     }
444
445     if (listen(g_acceptServerFD, caglobals.tcp.listenBacklog) != 0)
446     {
447         OIC_LOG(ERROR, TAG, "listen() error");
448         goto exit;
449     }
450
451     CHECKFD(g_acceptServerFD);
452
453     return CA_STATUS_OK;
454
455 exit:
456     if (g_acceptServerFD >= 0)
457     {
458         close(g_acceptServerFD);
459         g_acceptServerFD = -1;
460     }
461     return CA_STATUS_FAILED;
462 }
463
464 static void CAInitializePipe()
465 {
466     int ret = pipe(caglobals.tcp.shutdownFds);
467     if (-1 != ret)
468     {
469         ret = fcntl(caglobals.tcp.shutdownFds[0], F_GETFD);
470         if (-1 != ret)
471         {
472             ret = fcntl(caglobals.tcp.shutdownFds[0], F_SETFD, ret|FD_CLOEXEC);
473         }
474         if (-1 != ret)
475         {
476             ret = fcntl(caglobals.tcp.shutdownFds[1], F_GETFD);
477         }
478         if (-1 != ret)
479         {
480             ret = fcntl(caglobals.tcp.shutdownFds[1], F_SETFD, ret|FD_CLOEXEC);
481         }
482         if (-1 == ret)
483         {
484             close(caglobals.tcp.shutdownFds[1]);
485             close(caglobals.tcp.shutdownFds[0]);
486
487             caglobals.tcp.shutdownFds[0] = -1;
488             caglobals.tcp.shutdownFds[1] = -1;
489
490             OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
491         }
492     }
493 }
494
495 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
496 {
497     if (caglobals.tcp.started)
498     {
499         return CA_STATUS_OK;
500     }
501
502     if (!caglobals.tcp.ipv4tcpenabled)
503     {
504         caglobals.tcp.ipv4tcpenabled = true;    // only needed to run CA tests
505     }
506
507     CAResult_t res = CATCPCreateMutex();
508     if (CA_STATUS_OK == res)
509     {
510         res = CATCPCreateCond();
511     }
512     if (CA_STATUS_OK != res)
513     {
514         OIC_LOG(ERROR, TAG, "failed to create mutex/cond");
515         return res;
516     }
517
518     ca_mutex_lock(g_mutexObjectList);
519     if (!caglobals.tcp.svrlist)
520     {
521         caglobals.tcp.svrlist = u_arraylist_create();
522     }
523     ca_mutex_unlock(g_mutexObjectList);
524
525     res = CACreateAcceptSocket();
526     if (CA_STATUS_OK != res)
527     {
528         OIC_LOG(ERROR, TAG, "failed to create accept socket");
529         return res;
530     }
531
532     // create pipe for fast shutdown
533     CAInitializePipe();
534     CHECKFD(caglobals.tcp.shutdownFds[0]);
535     CHECKFD(caglobals.tcp.shutdownFds[1]);
536
537     caglobals.tcp.terminate = false;
538     res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
539     if (CA_STATUS_OK != res)
540     {
541         OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
542         return res;
543     }
544     OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
545
546     caglobals.tcp.started = true;
547     return CA_STATUS_OK;
548 }
549
550 void CATCPStopServer()
551 {
552     // mutex lock
553     ca_mutex_lock(g_mutexObjectList);
554
555     // set terminate flag
556     caglobals.tcp.terminate = true;
557     caglobals.tcp.started = false;
558
559     if (caglobals.tcp.shutdownFds[1] != -1)
560     {
561         close(caglobals.tcp.shutdownFds[1]);
562         // receive thread will stop immediately
563     }
564
565     ca_cond_wait(g_condObjectList, g_mutexObjectList);
566
567     // mutex unlock
568     ca_mutex_unlock(g_mutexObjectList);
569
570     if (-1 != g_acceptServerFD)
571     {
572         close(g_acceptServerFD);
573         g_acceptServerFD = -1;
574     }
575
576     CATCPDisconnectAll();
577     CATCPDestroyMutex();
578     CATCPDestroyCond();
579 }
580
581 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
582 {
583     g_packetReceivedCallback = callback;
584 }
585
586 static size_t CACheckPayloadLength(const void *data, size_t dlen)
587 {
588     VERIFY_NON_NULL_RET(data, TAG, "data", -1);
589
590     coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
591             ((unsigned char *)data)[0] >> 4);
592
593     coap_pdu_t *pdu = coap_new_pdu(transport, dlen);
594     if (!pdu)
595     {
596         OIC_LOG(ERROR, TAG, "outpdu is null");
597         return 0;
598     }
599
600     int ret = coap_pdu_parse((unsigned char *) data, dlen, pdu, transport);
601     if (0 >= ret)
602     {
603         OIC_LOG(ERROR, TAG, "pdu parse failed");
604         coap_delete_pdu(pdu);
605         return 0;
606     }
607
608     size_t payloadLen = 0;
609     size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
610     OIC_LOG_V(DEBUG, TAG, "headerSize : %d, pdu length : %d",
611               headerSize, pdu->length);
612     if (pdu->length > headerSize)
613     {
614         payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
615     }
616
617     OICFree(pdu);
618
619     return payloadLen;
620 }
621
622 static void sendData(const CAEndpoint_t *endpoint,
623                      const void *data, size_t dlen)
624 {
625     // #1. get TCP Server object from list
626     size_t index = 0;
627     CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
628     if (!svritem)
629     {
630         // if there is no connection info, connect to TCP Server
631         svritem = CAConnectTCPSession(endpoint);
632         if (!svritem)
633         {
634             OIC_LOG(ERROR, TAG, "Failed to create TCP server object");
635             g_TCPErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
636             return;
637         }
638     }
639
640     // #2. check payload length
641     size_t payloadLen = CACheckPayloadLength(data, dlen);
642     // if payload length is zero, disconnect from TCP server
643     if (!payloadLen)
644     {
645         OIC_LOG(DEBUG, TAG, "payload length is zero, disconnect from remote device");
646         CADisconnectTCPSession(svritem, index);
647         return;
648     }
649
650     // #3. check connection state
651     if (svritem->fd < 0)
652     {
653         // if file descriptor value is wrong, remove TCP Server info from list
654         OIC_LOG(ERROR, TAG, "Failed to connect to TCP server");
655         CADisconnectTCPSession(svritem, index);
656         g_TCPErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
657         return;
658     }
659
660     // #4. send data to TCP Server
661     ssize_t remainLen = dlen;
662     do
663     {
664         ssize_t len = send(svritem->fd, data, remainLen, 0);
665         if (-1 == len)
666         {
667             if (EWOULDBLOCK != errno)
668             {
669                 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
670                 g_TCPErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
671                 return;
672             }
673             continue;
674         }
675         data += len;
676         remainLen -= len;
677     } while (remainLen > 0);
678
679     OIC_LOG_V(INFO, TAG, "unicast ipv4tcp sendTo is successful: %zu bytes", dlen);
680 }
681
682 void CATCPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
683                    bool isMulticast)
684 {
685     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
686     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
687
688     if (!isMulticast)
689     {
690         if (caglobals.tcp.ipv4tcpenabled && (endpoint->adapter & CA_ADAPTER_TCP))
691         {
692             sendData(endpoint, data, datalen);
693         }
694     }
695 }
696
697 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
698 {
699     VERIFY_NON_NULL(info, TAG, "info is NULL");
700     VERIFY_NON_NULL(size, TAG, "size is NULL");
701
702     return CA_NOT_SUPPORTED;
703 }
704
705 CATCPSessionInfo_t *CAConnectTCPSession(const CAEndpoint_t *endpoint)
706 {
707     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
708
709     // #1. create TCP server object
710     CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
711     if (!svritem)
712     {
713         OIC_LOG(ERROR, TAG, "Out of memory");
714         return NULL;
715     }
716     memcpy(svritem->endpoint.addr, endpoint->addr, sizeof(svritem->endpoint.addr));
717     svritem->endpoint.port = endpoint->port;
718
719     // #2. create the socket and connect to TCP server
720     if (caglobals.tcp.ipv4tcpenabled)
721     {
722         int fd = CATCPCreateSocket(AF_INET, svritem);
723         if (-1 == fd)
724         {
725             OICFree(svritem);
726             return NULL;
727         }
728
729         // #3. add TCP connection info to list
730         svritem->fd = fd;
731         ca_mutex_lock(g_mutexObjectList);
732         if (caglobals.tcp.svrlist)
733         {
734             bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
735             if (!res)
736             {
737                 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
738                 close(svritem->fd);
739                 OICFree(svritem);
740                 ca_mutex_unlock(g_mutexObjectList);
741                 return NULL;
742             }
743         }
744         ca_mutex_unlock(g_mutexObjectList);
745
746         CHECKFD(fd);
747     }
748
749     return svritem;
750 }
751
752 CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *svritem, size_t index)
753 {
754     VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
755
756     ca_mutex_lock(g_mutexObjectList);
757
758     // close the socket and remove TCP connection info in list
759     if (svritem->fd >= 0)
760     {
761         close(svritem->fd);
762     }
763     u_arraylist_remove(caglobals.tcp.svrlist, index);
764     OICFree(svritem->recvData);
765     OICFree(svritem);
766     ca_mutex_unlock(g_mutexObjectList);
767
768     return CA_STATUS_OK;
769 }
770
771 void CATCPDisconnectAll()
772 {
773     ca_mutex_lock(g_mutexObjectList);
774     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
775
776     CATCPSessionInfo_t *svritem = NULL;
777     for (size_t i = 0; i < length; i++)
778     {
779         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
780         if (svritem && svritem->fd >= 0)
781         {
782             shutdown(svritem->fd, SHUT_RDWR);
783             close(svritem->fd);
784             OICFree(svritem->recvData);
785         }
786     }
787     u_arraylist_destroy(caglobals.tcp.svrlist);
788     ca_mutex_unlock(g_mutexObjectList);
789 }
790
791 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint,
792                                                     size_t *index)
793 {
794     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
795     VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
796
797     // get connection info from list
798     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
799     for (size_t i = 0; i < length; i++)
800     {
801         CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
802                 caglobals.tcp.svrlist, i);
803         if (!svritem)
804         {
805             continue;
806         }
807
808         if (!strncmp(svritem->endpoint.addr, endpoint->addr, sizeof(svritem->endpoint.addr))
809                 && (svritem->endpoint.port == endpoint->port))
810         {
811             *index = i;
812             return svritem;
813         }
814     }
815
816     return NULL;
817 }
818
819 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
820 {
821     ca_mutex_lock(g_mutexObjectList);
822
823     // check from the last item.
824     CATCPSessionInfo_t *svritem = NULL;
825     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
826     for (size_t i = 0; i < length; i++)
827     {
828         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
829
830         if (svritem && svritem->fd == fd)
831         {
832             *index = i;
833             ca_mutex_unlock(g_mutexObjectList);
834             return svritem;
835         }
836     }
837
838     ca_mutex_unlock(g_mutexObjectList);
839
840     return NULL;
841 }
842
843 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
844 {
845     OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
846
847     coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
848             ((unsigned char *)recvBuffer)[0] >> 4);
849     size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
850                                                         transport);
851     size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
852
853     OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%d]", optPaylaodLen);
854     OIC_LOG_V(DEBUG, TAG, "header length [%d]", headerLen);
855     OIC_LOG_V(DEBUG, TAG, "total data length [%d]", headerLen + optPaylaodLen);
856
857     OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
858     return headerLen + optPaylaodLen;
859 }
860
861 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
862 {
863     g_TCPErrorHandler = errorHandleCallback;
864 }