Imported Upstream version 1.1.0
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / tcp_adapter / catcpserver.c
1 /* ****************************************************************
2  *
3  * Copyright 2015 Samsung Electronics All Rights Reserved.
4  *
5  *
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  ******************************************************************/
20
21 #include <sys/types.h>
22 #include <sys/socket.h>
23 #include <sys/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     if (g_acceptServerFD != -1)
440     {
441         OIC_LOG(DEBUG, TAG, "accept socket created already");
442         return CA_STATUS_OK;
443     }
444
445     int reuse = 1;
446     struct sockaddr_in server = { .sin_addr.s_addr = INADDR_ANY,
447                                   .sin_family = AF_INET,
448                                   .sin_port = htons(SERVER_PORT),
449                                   .sin_zero = { 0 } };
450
451     g_acceptServerFD = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
452     if (g_acceptServerFD < 0)
453     {
454         OIC_LOG(ERROR, TAG, "Failed to create socket");
455         goto exit;
456     }
457
458     if (-1 == setsockopt(g_acceptServerFD, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
459     {
460         OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
461         goto exit;
462     }
463
464     int serverlen = sizeof(server);
465     if (-1 == bind(g_acceptServerFD, (struct sockaddr *)&server, serverlen))
466     {
467         OIC_LOG(ERROR, TAG, "bind() error");
468         goto exit;
469     }
470
471     if (listen(g_acceptServerFD, caglobals.tcp.listenBacklog) != 0)
472     {
473         OIC_LOG(ERROR, TAG, "listen() error");
474         goto exit;
475     }
476
477     CHECKFD(g_acceptServerFD);
478
479     return CA_STATUS_OK;
480
481 exit:
482     if (g_acceptServerFD >= 0)
483     {
484         close(g_acceptServerFD);
485         g_acceptServerFD = -1;
486     }
487     return CA_STATUS_FAILED;
488 }
489
490 static void CAInitializePipe(int *fds)
491 {
492     int ret = pipe(fds);
493     if (-1 != ret)
494     {
495         ret = fcntl(fds[0], F_GETFD);
496         if (-1 != ret)
497         {
498             ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
499         }
500         if (-1 != ret)
501         {
502             ret = fcntl(fds[1], F_GETFD);
503         }
504         if (-1 != ret)
505         {
506             ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
507         }
508         if (-1 == ret)
509         {
510             close(fds[1]);
511             close(fds[0]);
512
513             fds[0] = -1;
514             fds[1] = -1;
515
516             OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
517         }
518     }
519 }
520
521 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
522 {
523     if (caglobals.tcp.started)
524     {
525         return CA_STATUS_OK;
526     }
527
528     if (!caglobals.tcp.ipv4tcpenabled)
529     {
530         caglobals.tcp.ipv4tcpenabled = true;    // only needed to run CA tests
531     }
532
533     CAResult_t res = CATCPCreateMutex();
534     if (CA_STATUS_OK == res)
535     {
536         res = CATCPCreateCond();
537     }
538     if (CA_STATUS_OK != res)
539     {
540         OIC_LOG(ERROR, TAG, "failed to create mutex/cond");
541         return res;
542     }
543
544     ca_mutex_lock(g_mutexObjectList);
545     if (!caglobals.tcp.svrlist)
546     {
547         caglobals.tcp.svrlist = u_arraylist_create();
548     }
549     ca_mutex_unlock(g_mutexObjectList);
550
551     if (caglobals.server)
552     {
553         res = CACreateAcceptSocket();
554         if (CA_STATUS_OK != res)
555         {
556             OIC_LOG(ERROR, TAG, "failed to create accept socket");
557             return res;
558         }
559     }
560
561     // create pipe for fast shutdown
562     CAInitializePipe(caglobals.tcp.shutdownFds);
563     CHECKFD(caglobals.tcp.shutdownFds[0]);
564     CHECKFD(caglobals.tcp.shutdownFds[1]);
565
566     // create pipe for connection event
567     CAInitializePipe(caglobals.tcp.connectionFds);
568     CHECKFD(caglobals.tcp.connectionFds[0]);
569     CHECKFD(caglobals.tcp.connectionFds[1]);
570
571     caglobals.tcp.terminate = false;
572     res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
573     if (CA_STATUS_OK != res)
574     {
575         OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
576         return res;
577     }
578     OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
579
580     caglobals.tcp.started = true;
581     return CA_STATUS_OK;
582 }
583
584 void CATCPStopServer()
585 {
586     // mutex lock
587     ca_mutex_lock(g_mutexObjectList);
588
589     // set terminate flag
590     caglobals.tcp.terminate = true;
591
592     if (caglobals.tcp.shutdownFds[1] != -1)
593     {
594         close(caglobals.tcp.shutdownFds[1]);
595         // receive thread will stop immediately
596     }
597
598     if (caglobals.tcp.connectionFds[1] != -1)
599     {
600         close(caglobals.tcp.connectionFds[1]);
601     }
602
603     if (caglobals.tcp.started)
604     {
605         ca_cond_wait(g_condObjectList, g_mutexObjectList);
606     }
607     caglobals.tcp.started = false;
608
609     // mutex unlock
610     ca_mutex_unlock(g_mutexObjectList);
611
612     if (-1 != g_acceptServerFD)
613     {
614         close(g_acceptServerFD);
615         g_acceptServerFD = -1;
616     }
617
618     CATCPDisconnectAll();
619     CATCPDestroyMutex();
620     CATCPDestroyCond();
621 }
622
623 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
624 {
625     g_packetReceivedCallback = callback;
626 }
627
628 void CATCPSetKeepAliveCallback(CATCPKeepAliveHandleCallback keepaliveHandler)
629 {
630     g_keepaliveCallback = keepaliveHandler;
631 }
632
633 static size_t CACheckPayloadLength(const void *data, size_t dlen)
634 {
635     VERIFY_NON_NULL_RET(data, TAG, "data", -1);
636
637     coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
638             ((unsigned char *)data)[0] >> 4);
639
640     coap_pdu_t *pdu = coap_new_pdu(transport, dlen);
641     if (!pdu)
642     {
643         OIC_LOG(ERROR, TAG, "outpdu is null");
644         return 0;
645     }
646
647     int ret = coap_pdu_parse((unsigned char *) data, dlen, pdu, transport);
648     if (0 >= ret)
649     {
650         OIC_LOG(ERROR, TAG, "pdu parse failed");
651         coap_delete_pdu(pdu);
652         return 0;
653     }
654
655     size_t payloadLen = 0;
656     size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
657     OIC_LOG_V(DEBUG, TAG, "headerSize : %d, pdu length : %d",
658               headerSize, pdu->length);
659     if (pdu->length > headerSize)
660     {
661         payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
662     }
663
664     OICFree(pdu);
665
666     return payloadLen;
667 }
668
669 static void sendData(const CAEndpoint_t *endpoint,
670                      const void *data, size_t dlen)
671 {
672     // #1. get TCP Server object from list
673     size_t index = 0;
674     CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
675     if (!svritem)
676     {
677         // if there is no connection info, connect to TCP Server
678         svritem = CAConnectTCPSession(endpoint);
679         if (!svritem)
680         {
681             OIC_LOG(ERROR, TAG, "Failed to create TCP server object");
682             g_TCPErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
683             return;
684         }
685     }
686
687     // #2. check payload length
688     size_t payloadLen = CACheckPayloadLength(data, dlen);
689     // if payload length is zero, disconnect from TCP server
690     if (!payloadLen)
691     {
692         OIC_LOG(DEBUG, TAG, "payload length is zero, disconnect from remote device");
693         CADisconnectTCPSession(svritem, index);
694         return;
695     }
696
697     // #3. check connection state
698     if (svritem->fd < 0)
699     {
700         // if file descriptor value is wrong, remove TCP Server info from list
701         OIC_LOG(ERROR, TAG, "Failed to connect to TCP server");
702         CADisconnectTCPSession(svritem, index);
703         g_TCPErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
704         return;
705     }
706
707     // #4. send data to TCP Server
708     ssize_t remainLen = dlen;
709     do
710     {
711         ssize_t len = send(svritem->fd, data, remainLen, 0);
712         if (-1 == len)
713         {
714             if (EWOULDBLOCK != errno)
715             {
716                 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
717                 g_TCPErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
718                 return;
719             }
720             continue;
721         }
722         data += len;
723         remainLen -= len;
724     } while (remainLen > 0);
725
726     OIC_LOG_V(INFO, TAG, "unicast ipv4tcp sendTo is successful: %zu bytes", dlen);
727 }
728
729 void CATCPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
730                    bool isMulticast)
731 {
732     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
733     VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
734
735     if (!isMulticast)
736     {
737         if (caglobals.tcp.ipv4tcpenabled && (endpoint->adapter & CA_ADAPTER_TCP))
738         {
739             sendData(endpoint, data, datalen);
740         }
741     }
742 }
743
744 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
745 {
746     VERIFY_NON_NULL(info, TAG, "info is NULL");
747     VERIFY_NON_NULL(size, TAG, "size is NULL");
748
749     return CA_NOT_SUPPORTED;
750 }
751
752 CATCPSessionInfo_t *CAConnectTCPSession(const CAEndpoint_t *endpoint)
753 {
754     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
755
756     // #1. create TCP server object
757     CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
758     if (!svritem)
759     {
760         OIC_LOG(ERROR, TAG, "Out of memory");
761         return NULL;
762     }
763     memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
764     svritem->sep.endpoint.port = endpoint->port;
765
766     // #2. create the socket and connect to TCP server
767     if (caglobals.tcp.ipv4tcpenabled)
768     {
769         int fd = CATCPCreateSocket(AF_INET, svritem);
770         if (-1 == fd)
771         {
772             OICFree(svritem);
773             return NULL;
774         }
775
776         // #3. add TCP connection info to list
777         svritem->fd = fd;
778         ca_mutex_lock(g_mutexObjectList);
779         if (caglobals.tcp.svrlist)
780         {
781             bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
782             if (!res)
783             {
784                 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
785                 close(svritem->fd);
786                 OICFree(svritem);
787                 ca_mutex_unlock(g_mutexObjectList);
788                 return NULL;
789             }
790         }
791         ca_mutex_unlock(g_mutexObjectList);
792
793         CHECKFD(fd);
794
795         // pass the connection information to RI for keepalive.
796         if (g_keepaliveCallback)
797         {
798             g_keepaliveCallback(svritem->sep.endpoint.addr, svritem->sep.endpoint.port, true);
799         }
800     }
801
802     return svritem;
803 }
804
805 CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *svritem, size_t index)
806 {
807     VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
808
809     ca_mutex_lock(g_mutexObjectList);
810
811     // close the socket and remove TCP connection info in list
812     if (svritem->fd >= 0)
813     {
814         close(svritem->fd);
815     }
816     u_arraylist_remove(caglobals.tcp.svrlist, index);
817     OICFree(svritem->recvData);
818     OICFree(svritem);
819     ca_mutex_unlock(g_mutexObjectList);
820
821     // pass the connection information to RI for keepalive.
822     if (g_keepaliveCallback)
823     {
824         g_keepaliveCallback(svritem->sep.endpoint.addr, svritem->sep.endpoint.port, false);
825     }
826
827     return CA_STATUS_OK;
828 }
829
830 void CATCPDisconnectAll()
831 {
832     ca_mutex_lock(g_mutexObjectList);
833     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
834
835     CATCPSessionInfo_t *svritem = NULL;
836     for (size_t i = 0; i < length; i++)
837     {
838         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
839         if (svritem && svritem->fd >= 0)
840         {
841             shutdown(svritem->fd, SHUT_RDWR);
842             close(svritem->fd);
843             OICFree(svritem->recvData);
844         }
845     }
846     u_arraylist_destroy(caglobals.tcp.svrlist);
847     ca_mutex_unlock(g_mutexObjectList);
848 }
849
850 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint,
851                                                     size_t *index)
852 {
853     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
854     VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
855
856     // get connection info from list
857     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
858     for (size_t i = 0; i < length; i++)
859     {
860         CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
861                 caglobals.tcp.svrlist, i);
862         if (!svritem)
863         {
864             continue;
865         }
866
867         if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
868                      sizeof(svritem->sep.endpoint.addr))
869                 && (svritem->sep.endpoint.port == endpoint->port))
870         {
871             *index = i;
872             return svritem;
873         }
874     }
875
876     return NULL;
877 }
878
879 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
880 {
881     ca_mutex_lock(g_mutexObjectList);
882
883     // check from the last item.
884     CATCPSessionInfo_t *svritem = NULL;
885     uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
886     for (size_t i = 0; i < length; i++)
887     {
888         svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
889
890         if (svritem && svritem->fd == fd)
891         {
892             *index = i;
893             ca_mutex_unlock(g_mutexObjectList);
894             return svritem;
895         }
896     }
897
898     ca_mutex_unlock(g_mutexObjectList);
899
900     return NULL;
901 }
902
903 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
904 {
905     OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
906
907     coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
908             ((unsigned char *)recvBuffer)[0] >> 4);
909     size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
910                                                         transport);
911     size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
912
913     OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%d]", optPaylaodLen);
914     OIC_LOG_V(DEBUG, TAG, "header length [%d]", headerLen);
915     OIC_LOG_V(DEBUG, TAG, "total data length [%d]", headerLen + optPaylaodLen);
916
917     OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
918     return headerLen + optPaylaodLen;
919 }
920
921 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
922 {
923     g_TCPErrorHandler = errorHandleCallback;
924 }