Fix CA Layer build warnings
[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->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     caglobals.tcp.started = false;
559
560     if (caglobals.tcp.shutdownFds[1] != -1)
561     {
562         close(caglobals.tcp.shutdownFds[1]);
563         // receive thread will stop immediately
564     }
565
566     ca_cond_wait(g_condObjectList, g_mutexObjectList);
567
568     // mutex unlock
569     ca_mutex_unlock(g_mutexObjectList);
570
571     if (-1 != g_acceptServerFD)
572     {
573         close(g_acceptServerFD);
574         g_acceptServerFD = -1;
575     }
576
577     CATCPDisconnectAll();
578     CATCPDestroyMutex();
579     CATCPDestroyCond();
580 }
581
582 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
583 {
584     g_packetReceivedCallback = callback;
585 }
586
587 static size_t CACheckPayloadLength(const void *data, size_t dlen)
588 {
589     VERIFY_NON_NULL_RET(data, TAG, "data", -1);
590
591     coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
592             ((unsigned char *)data)[0] >> 4);
593
594     coap_pdu_t *pdu = coap_new_pdu(transport, dlen);
595     if (!pdu)
596     {
597         OIC_LOG(ERROR, TAG, "outpdu is null");
598         return 0;
599     }
600
601     int ret = coap_pdu_parse((unsigned char *) data, dlen, pdu, transport);
602     if (0 >= ret)
603     {
604         OIC_LOG(ERROR, TAG, "pdu parse failed");
605         coap_delete_pdu(pdu);
606         return 0;
607     }
608
609     size_t payloadLen = 0;
610     size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
611     OIC_LOG_V(DEBUG, TAG, "headerSize : %d, pdu length : %d",
612               headerSize, pdu->length);
613     if (pdu->length > headerSize)
614     {
615         payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
616     }
617
618     OICFree(pdu);
619
620     return payloadLen;
621 }
622
623 static void sendData(const CAEndpoint_t *endpoint,
624                      const void *data, size_t dlen)
625 {
626     // #1. get TCP Server object from list
627     size_t index = 0;
628     CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
629     if (!svritem)
630     {
631         // if there is no connection info, connect to TCP Server
632         svritem = CAConnectTCPSession(endpoint);
633         if (!svritem)
634         {
635             OIC_LOG(ERROR, TAG, "Failed to create TCP server object");
636             g_TCPErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
637             return;
638         }
639     }
640
641     // #2. check payload length
642     size_t payloadLen = CACheckPayloadLength(data, dlen);
643     // if payload length is zero, disconnect from TCP server
644     if (!payloadLen)
645     {
646         OIC_LOG(DEBUG, TAG, "payload length is zero, disconnect from remote device");
647         CADisconnectTCPSession(svritem, index);
648         return;
649     }
650
651     // #3. check connection state
652     if (svritem->fd < 0)
653     {
654         // if file descriptor value is wrong, remove TCP Server info from list
655         OIC_LOG(ERROR, TAG, "Failed to connect to TCP server");
656         CADisconnectTCPSession(svritem, index);
657         g_TCPErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
658         return;
659     }
660
661     // #4. send data to TCP Server
662     ssize_t remainLen = dlen;
663     do
664     {
665         ssize_t len = send(svritem->fd, data, remainLen, 0);
666         if (-1 == len)
667         {
668             if (EWOULDBLOCK != errno)
669             {
670                 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
671                 g_TCPErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
672                 return;
673             }
674             continue;
675         }
676         data += len;
677         remainLen -= len;
678     } while (remainLen > 0);
679
680     OIC_LOG_V(INFO, TAG, "unicast ipv4tcp sendTo is successful: %zu bytes", dlen);
681 }
682
683 void CATCPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
684                    bool isMulticast)
685 {
686     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
687     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
688
689     if (!isMulticast)
690     {
691         if (caglobals.tcp.ipv4tcpenabled && (endpoint->adapter & CA_ADAPTER_TCP))
692         {
693             sendData(endpoint, data, datalen);
694         }
695     }
696 }
697
698 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
699 {
700     VERIFY_NON_NULL(info, TAG, "info is NULL");
701     VERIFY_NON_NULL(size, TAG, "size is NULL");
702
703     return CA_NOT_SUPPORTED;
704 }
705
706 CATCPSessionInfo_t *CAConnectTCPSession(const CAEndpoint_t *endpoint)
707 {
708     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
709
710     // #1. create TCP server object
711     CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
712     if (!svritem)
713     {
714         OIC_LOG(ERROR, TAG, "Out of memory");
715         return NULL;
716     }
717     memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
718     svritem->sep.endpoint.port = endpoint->port;
719
720     // #2. create the socket and connect to TCP server
721     if (caglobals.tcp.ipv4tcpenabled)
722     {
723         int fd = CATCPCreateSocket(AF_INET, svritem);
724         if (-1 == fd)
725         {
726             OICFree(svritem);
727             return NULL;
728         }
729
730         // #3. add TCP connection info to list
731         svritem->fd = fd;
732         ca_mutex_lock(g_mutexObjectList);
733         if (caglobals.tcp.svrlist)
734         {
735             bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
736             if (!res)
737             {
738                 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
739                 close(svritem->fd);
740                 OICFree(svritem);
741                 ca_mutex_unlock(g_mutexObjectList);
742                 return NULL;
743             }
744         }
745         ca_mutex_unlock(g_mutexObjectList);
746
747         CHECKFD(fd);
748     }
749
750     return svritem;
751 }
752
753 CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *svritem, size_t index)
754 {
755     VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
756
757     ca_mutex_lock(g_mutexObjectList);
758
759     // close the socket and remove TCP connection info in list
760     if (svritem->fd >= 0)
761     {
762         close(svritem->fd);
763     }
764     u_arraylist_remove(caglobals.tcp.svrlist, index);
765     OICFree(svritem->recvData);
766     OICFree(svritem);
767     ca_mutex_unlock(g_mutexObjectList);
768
769     return CA_STATUS_OK;
770 }
771
772 void CATCPDisconnectAll()
773 {
774     ca_mutex_lock(g_mutexObjectList);
775     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
776
777     CATCPSessionInfo_t *svritem = NULL;
778     for (size_t i = 0; i < length; i++)
779     {
780         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
781         if (svritem && svritem->fd >= 0)
782         {
783             shutdown(svritem->fd, SHUT_RDWR);
784             close(svritem->fd);
785             OICFree(svritem->recvData);
786         }
787     }
788     u_arraylist_destroy(caglobals.tcp.svrlist);
789     ca_mutex_unlock(g_mutexObjectList);
790 }
791
792 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint,
793                                                     size_t *index)
794 {
795     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
796     VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
797
798     // get connection info from list
799     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
800     for (size_t i = 0; i < length; i++)
801     {
802         CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
803                 caglobals.tcp.svrlist, i);
804         if (!svritem)
805         {
806             continue;
807         }
808
809         if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
810                      sizeof(svritem->sep.endpoint.addr))
811                 && (svritem->sep.endpoint.port == endpoint->port))
812         {
813             *index = i;
814             return svritem;
815         }
816     }
817
818     return NULL;
819 }
820
821 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
822 {
823     ca_mutex_lock(g_mutexObjectList);
824
825     // check from the last item.
826     CATCPSessionInfo_t *svritem = NULL;
827     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
828     for (size_t i = 0; i < length; i++)
829     {
830         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
831
832         if (svritem && svritem->fd == fd)
833         {
834             *index = i;
835             ca_mutex_unlock(g_mutexObjectList);
836             return svritem;
837         }
838     }
839
840     ca_mutex_unlock(g_mutexObjectList);
841
842     return NULL;
843 }
844
845 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
846 {
847     OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
848
849     coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
850             ((unsigned char *)recvBuffer)[0] >> 4);
851     size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
852                                                         transport);
853     size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
854
855     OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%d]", optPaylaodLen);
856     OIC_LOG_V(DEBUG, TAG, "header length [%d]", headerLen);
857     OIC_LOG_V(DEBUG, TAG, "total data length [%d]", headerLen + optPaylaodLen);
858
859     OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
860     return headerLen + optPaylaodLen;
861 }
862
863 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
864 {
865     g_TCPErrorHandler = errorHandleCallback;
866 }