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