1 /* ****************************************************************
3 * Copyright 2015 Samsung Electronics All Rights Reserved.
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 ******************************************************************/
21 #include <sys/types.h>
22 #include <sys/socket.h>
23 #include <sys/select.h>
24 #include <sys/ioctl.h>
29 #include <arpa/inet.h>
30 #include <netinet/in.h>
35 #include <sys/socket.h>
36 #include <netinet/in.h>
40 #include "catcpinterface.h"
42 #include "caadapterutils.h"
44 #include "oic_malloc.h"
45 #include "oic_string.h"
48 * Logging tag for module name.
50 #define TAG "OIC_CA_TCP_SERVER"
53 * Maximum CoAP over TCP header length
54 * to know the total data length.
56 #define TCP_MAX_HEADER_LEN 6
59 * Mutex to synchronize device object list.
61 static ca_mutex g_mutexObjectList = NULL;
64 * Conditional mutex to synchronize.
66 static ca_cond g_condObjectList = NULL;
69 * Maintains the callback to be notified when data received from remote device.
71 static CATCPPacketReceivedCallback g_packetReceivedCallback = NULL;
74 * Error callback to update error in TCP.
76 static CATCPErrorHandleCallback g_tcpErrorHandler = NULL;
79 * Connected Callback to pass the connection information to RI.
81 static CATCPConnectionHandleCallback g_connectionCallback = NULL;
83 static CAResult_t CATCPCreateMutex();
84 static void CATCPDestroyMutex();
85 static CAResult_t CATCPCreateCond();
86 static void CATCPDestroyCond();
87 static int CACreateAcceptSocket(int family, CASocket_t *sock);
88 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock);
89 static void CAFindReadyMessage();
90 static void CASelectReturned(fd_set *readFds);
91 static void CAReceiveMessage(int fd);
92 static void CAReceiveHandler(void *data);
93 static int CATCPCreateSocket(int family, CATCPSessionInfo_t *tcpServerInfo);
96 if (FD > caglobals.tcp.maxfd) \
97 caglobals.tcp.maxfd = FD;
99 static void CATCPDestroyMutex()
101 if (g_mutexObjectList)
103 ca_mutex_free(g_mutexObjectList);
104 g_mutexObjectList = NULL;
108 static CAResult_t CATCPCreateMutex()
110 if (!g_mutexObjectList)
112 g_mutexObjectList = ca_mutex_new();
113 if (!g_mutexObjectList)
115 OIC_LOG(ERROR, TAG, "Failed to created mutex!");
116 return CA_STATUS_FAILED;
123 static void CATCPDestroyCond()
125 if (g_condObjectList)
127 ca_cond_free(g_condObjectList);
128 g_condObjectList = NULL;
132 static CAResult_t CATCPCreateCond()
134 if (!g_condObjectList)
136 g_condObjectList = ca_cond_new();
137 if (!g_condObjectList)
139 OIC_LOG(ERROR, TAG, "Failed to created cond!");
140 return CA_STATUS_FAILED;
146 static void CAReceiveHandler(void *data)
149 OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler");
151 while (!caglobals.tcp.terminate)
153 CAFindReadyMessage();
156 ca_mutex_lock(g_mutexObjectList);
157 ca_cond_signal(g_condObjectList);
158 ca_mutex_unlock(g_mutexObjectList);
160 OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
163 static void CAFindReadyMessage()
166 struct timeval timeout = { .tv_sec = caglobals.tcp.selectTimeout };
170 if (-1 != caglobals.tcp.ipv4.fd)
172 FD_SET(caglobals.tcp.ipv4.fd, &readFds);
174 if (-1 != caglobals.tcp.ipv6.fd)
176 FD_SET(caglobals.tcp.ipv6.fd, &readFds);
178 if (-1 != caglobals.tcp.shutdownFds[0])
180 FD_SET(caglobals.tcp.shutdownFds[0], &readFds);
182 if (-1 != caglobals.tcp.connectionFds[0])
184 FD_SET(caglobals.tcp.connectionFds[0], &readFds);
187 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
188 for (size_t i = 0; i < length; i++)
190 CATCPSessionInfo_t *svritem =
191 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
192 if (svritem && 0 <= svritem->fd)
194 FD_SET(svritem->fd, &readFds);
198 int ret = select(caglobals.tcp.maxfd + 1, &readFds, NULL, NULL, &timeout);
200 if (caglobals.tcp.terminate)
202 OIC_LOG_V(DEBUG, TAG, "Packet receiver Stop request received.");
209 OIC_LOG_V(FATAL, TAG, "select error %s", strerror(errno));
214 CASelectReturned(&readFds);
217 static void CASelectReturned(fd_set *readFds)
219 VERIFY_NON_NULL_VOID(readFds, TAG, "readFds is NULL");
221 if (caglobals.tcp.ipv4.fd != -1 && FD_ISSET(caglobals.tcp.ipv4.fd, readFds))
223 CAAcceptConnection(CA_IPV4, &caglobals.tcp.ipv4);
226 else if (caglobals.tcp.ipv6.fd != -1 && FD_ISSET(caglobals.tcp.ipv6.fd, readFds))
228 CAAcceptConnection(CA_IPV6, &caglobals.tcp.ipv6);
231 else if (-1 != caglobals.tcp.connectionFds[0] &&
232 FD_ISSET(caglobals.tcp.connectionFds[0], readFds))
234 // new connection was created from remote device.
235 // exit the function to update read file descriptor.
236 char buf[MAX_ADDR_STR_SIZE_CA] = {0};
237 ssize_t len = read(caglobals.tcp.connectionFds[0], buf, sizeof (buf));
242 OIC_LOG_V(DEBUG, TAG, "Received new connection event with [%s]", buf);
243 FD_CLR(caglobals.tcp.connectionFds[0], readFds);
246 else if (-1 != caglobals.tcp.connectionFds[0] &&
247 FD_ISSET(caglobals.tcp.connectionFds[0], readFds))
249 // new connection was created from remote device.
250 // exit the function to update read file descriptor.
251 char buf[MAX_ADDR_STR_SIZE_CA] = {0};
252 ssize_t len = read(caglobals.tcp.connectionFds[0], buf, sizeof (buf));
257 OIC_LOG_V(DEBUG, TAG, "Received new connection event with [%s]", buf);
258 FD_CLR(caglobals.tcp.connectionFds[0], readFds);
263 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
264 for (size_t i = 0; i < length; i++)
266 CATCPSessionInfo_t *svritem =
267 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
268 if (svritem && svritem->fd >= 0)
270 if (FD_ISSET(svritem->fd, readFds))
272 CAReceiveMessage(svritem->fd);
273 FD_CLR(svritem->fd, readFds);
280 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock)
282 VERIFY_NON_NULL_VOID(sock, TAG, "sock is NULL");
284 struct sockaddr_storage clientaddr;
285 socklen_t clientlen = sizeof (struct sockaddr_in);
288 clientlen = sizeof(struct sockaddr_in6);
291 int sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen);
294 CATCPSessionInfo_t *svritem =
295 (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
298 OIC_LOG(ERROR, TAG, "Out of memory");
303 svritem->fd = sockfd;
304 svritem->sep.endpoint.flags = flag;
305 CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
306 svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
308 ca_mutex_lock(g_mutexObjectList);
309 bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem);
312 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
315 ca_mutex_unlock(g_mutexObjectList);
318 ca_mutex_unlock(g_mutexObjectList);
324 static void CAReceiveMessage(int fd)
326 // #1. get remote device information from file descriptor.
328 CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFD(fd, &index);
331 OIC_LOG(ERROR, TAG, "there is no connection information in list");
335 // #2. get already allocated memory size.
336 size_t bufSize = (svritem->totalDataLen == 0) ? TCP_MAX_HEADER_LEN : svritem->totalDataLen;
337 if (!svritem->recvData)
339 svritem->recvData = (unsigned char *) OICCalloc(1, bufSize);
340 if (!svritem->recvData)
342 OIC_LOG(ERROR, TAG, "out of memory");
343 CADisconnectTCPSession(svritem, index);
348 // #3. receive data from remote device.
349 ssize_t recvLen = recv(fd, svritem->recvData + svritem->recvDataLen,
350 bufSize - svritem->recvDataLen, 0);
353 if(EWOULDBLOCK != errno)
355 OIC_LOG_V(ERROR, TAG, "Recvfrom failed %s", strerror(errno));
356 CADisconnectTCPSession(svritem, index);
360 svritem->recvDataLen += recvLen;
362 // #4. get actual data length from coap over tcp header.
363 if (!svritem->totalDataLen)
365 coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
366 ((unsigned char *) svritem->recvData)[0] >> 4);
368 size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
369 if (svritem->recvDataLen >= headerLen)
371 svritem->totalDataLen = CAGetTotalLengthFromHeader(
372 (unsigned char *) svritem->recvData);
373 bufSize = svritem->totalDataLen;
374 unsigned char *newBuf = OICRealloc(svritem->recvData, bufSize);
377 OIC_LOG(ERROR, TAG, "out of memory");
378 CADisconnectTCPSession(svritem, index);
381 svritem->recvData = newBuf;
385 // #5. pass the received data information to upper layer.
386 if ((svritem->totalDataLen == svritem->recvDataLen) && g_packetReceivedCallback)
388 svritem->sep.endpoint.adapter = CA_ADAPTER_TCP;
389 g_packetReceivedCallback(&svritem->sep, svritem->recvData, svritem->recvDataLen);
390 OIC_LOG_V(DEBUG, TAG, "total received data len:%d", svritem->recvDataLen);
392 // initialize data info to receive next message.
393 OICFree(svritem->recvData);
394 svritem->recvData = NULL;
395 svritem->recvDataLen = 0;
396 svritem->totalDataLen = 0;
402 static void CAWakeUpForReadFdsUpdate(const char *host)
404 if (caglobals.tcp.connectionFds[1] != -1)
409 len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
410 } while ((len == -1) && (errno == EINTR));
412 if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
414 OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
419 static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port,
420 struct sockaddr_storage *sockaddr)
422 struct addrinfo *addrs = NULL;
423 struct addrinfo hints = { .ai_family = family,
424 .ai_protocol = IPPROTO_TCP,
425 .ai_socktype = SOCK_STREAM,
426 .ai_flags = AI_NUMERICHOST };
428 int r = getaddrinfo(host, NULL, &hints, &addrs);
433 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: errno %s", strerror(errno));
437 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: %s", gai_strerror(r));
440 return CA_STATUS_FAILED;
442 // assumption: in this case, getaddrinfo will only return one addrinfo
443 // or first is the one we want.
444 if (addrs[0].ai_family == AF_INET6)
446 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6));
447 ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port);
451 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in));
452 ((struct sockaddr_in *)sockaddr)->sin_port = htons(port);
458 static int CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
460 // #1. create tcp socket.
461 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
464 OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
468 // #2. convert address from string to binary.
469 struct sockaddr_storage sa = { .ss_family = family };
470 CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr,
471 svritem->sep.endpoint.port, &sa);
472 if (CA_STATUS_OK != res)
478 // #3. set socket length.
479 socklen_t socklen = 0;
480 if (sa.ss_family == AF_INET6)
482 struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
483 if (!sock6->sin6_scope_id)
485 sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
487 socklen = sizeof(struct sockaddr_in6);
491 socklen = sizeof(struct sockaddr_in);
494 // #4. connect to remote server device.
495 if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
497 OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
502 OIC_LOG(DEBUG, TAG, "connect socket success");
503 CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
507 static int CACreateAcceptSocket(int family, CASocket_t *sock)
509 VERIFY_NON_NULL_RET(sock, TAG, "sock", -1);
513 OIC_LOG(DEBUG, TAG, "accept socket created already");
517 socklen_t socklen = 0;
518 struct sockaddr_storage server = { .ss_family = family };
520 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
523 OIC_LOG(ERROR, TAG, "Failed to create socket");
527 if (family == AF_INET6)
529 // the socket is re‐stricted to sending and receiving IPv6 packets only.
531 if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
533 OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
536 ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port);
537 socklen = sizeof (struct sockaddr_in6);
541 ((struct sockaddr_in *)&server)->sin_port = htons(sock->port);
542 socklen = sizeof (struct sockaddr_in);
546 if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
548 OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
552 if (-1 == bind(fd, (struct sockaddr *)&server, socklen))
554 OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
558 if (listen(fd, caglobals.tcp.listenBacklog) != 0)
560 OIC_LOG(ERROR, TAG, "listen() error");
564 if (!sock->port) // return the assigned port
566 if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen))
568 OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
571 sock->port = ntohs(family == AF_INET6 ?
572 ((struct sockaddr_in6 *)&server)->sin6_port :
573 ((struct sockaddr_in *)&server)->sin_port);
586 static void CAInitializePipe(int *fds)
591 ret = fcntl(fds[0], F_GETFD);
594 ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
598 ret = fcntl(fds[1], F_GETFD);
602 ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
612 OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
617 #define NEWSOCKET(FAMILY, NAME) \
618 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
619 if (caglobals.tcp.NAME.fd == -1) \
621 caglobals.tcp.NAME.port = 0; \
622 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
624 CHECKFD(caglobals.tcp.NAME.fd);
626 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
628 if (caglobals.tcp.started)
633 if (!caglobals.tcp.ipv4tcpenabled)
635 caglobals.tcp.ipv4tcpenabled = true; // only needed to run CA tests
637 if (!caglobals.tcp.ipv6tcpenabled)
639 caglobals.tcp.ipv6tcpenabled = true; // only needed to run CA tests
642 CAResult_t res = CATCPCreateMutex();
643 if (CA_STATUS_OK == res)
645 res = CATCPCreateCond();
647 if (CA_STATUS_OK != res)
649 OIC_LOG(ERROR, TAG, "failed to create mutex/cond");
653 ca_mutex_lock(g_mutexObjectList);
654 if (!caglobals.tcp.svrlist)
656 caglobals.tcp.svrlist = u_arraylist_create();
658 ca_mutex_unlock(g_mutexObjectList);
660 if (caglobals.server)
662 NEWSOCKET(AF_INET, ipv4);
663 NEWSOCKET(AF_INET6, ipv6);
664 OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
665 caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
666 OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
667 caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
670 // create pipe for fast shutdown
671 CAInitializePipe(caglobals.tcp.shutdownFds);
672 CHECKFD(caglobals.tcp.shutdownFds[0]);
673 CHECKFD(caglobals.tcp.shutdownFds[1]);
675 // create pipe for connection event
676 CAInitializePipe(caglobals.tcp.connectionFds);
677 CHECKFD(caglobals.tcp.connectionFds[0]);
678 CHECKFD(caglobals.tcp.connectionFds[1]);
680 caglobals.tcp.terminate = false;
681 res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
682 if (CA_STATUS_OK != res)
684 OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
687 OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
689 caglobals.tcp.started = true;
693 void CATCPStopServer()
696 ca_mutex_lock(g_mutexObjectList);
698 // set terminate flag
699 caglobals.tcp.terminate = true;
701 if (caglobals.tcp.shutdownFds[1] != -1)
703 close(caglobals.tcp.shutdownFds[1]);
704 // receive thread will stop immediately
707 if (caglobals.tcp.connectionFds[1] != -1)
709 close(caglobals.tcp.connectionFds[1]);
712 if (caglobals.tcp.started)
714 ca_cond_wait(g_condObjectList, g_mutexObjectList);
716 caglobals.tcp.started = false;
719 ca_mutex_unlock(g_mutexObjectList);
721 if (-1 != caglobals.tcp.ipv4.fd)
723 close(caglobals.tcp.ipv4.fd);
724 caglobals.tcp.ipv4.fd = -1;
727 if (-1 != caglobals.tcp.ipv6.fd)
729 close(caglobals.tcp.ipv6.fd);
730 caglobals.tcp.ipv6.fd = -1;
733 CATCPDisconnectAll();
738 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
740 g_packetReceivedCallback = callback;
743 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
745 g_connectionCallback = connHandler;
748 static size_t CACheckPayloadLength(const void *data, size_t dlen)
750 VERIFY_NON_NULL_RET(data, TAG, "data", -1);
752 coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
753 ((unsigned char *)data)[0] >> 4);
755 coap_pdu_t *pdu = coap_new_pdu(transport, dlen);
758 OIC_LOG(ERROR, TAG, "outpdu is null");
762 int ret = coap_pdu_parse((unsigned char *) data, dlen, pdu, transport);
765 OIC_LOG(ERROR, TAG, "pdu parse failed");
766 coap_delete_pdu(pdu);
770 size_t payloadLen = 0;
771 size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
772 OIC_LOG_V(DEBUG, TAG, "headerSize : %d, pdu length : %d",
773 headerSize, pdu->length);
774 if (pdu->length > headerSize)
776 payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
784 static void sendData(const CAEndpoint_t *endpoint, const void *data,
785 size_t dlen, const char *fam)
787 // #1. get TCP Server object from list
789 CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
792 // if there is no connection info, connect to TCP Server
793 svritem = CAConnectTCPSession(endpoint);
796 OIC_LOG(ERROR, TAG, "Failed to create TCP server object");
797 if (g_tcpErrorHandler)
799 g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
805 // #2. check payload length
806 size_t payloadLen = CACheckPayloadLength(data, dlen);
807 // if payload length is zero, disconnect from TCP server
810 OIC_LOG(DEBUG, TAG, "payload length is zero, disconnect from remote device");
811 CADisconnectTCPSession(svritem, index);
815 // #3. check connection state
818 // if file descriptor value is wrong, remove TCP Server info from list
819 OIC_LOG(ERROR, TAG, "Failed to connect to TCP server");
820 CADisconnectTCPSession(svritem, index);
821 if (g_tcpErrorHandler)
823 g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
828 // #4. send data to TCP Server
829 ssize_t remainLen = dlen;
832 ssize_t len = send(svritem->fd, data, remainLen, 0);
835 if (EWOULDBLOCK != errno)
837 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
838 if (g_tcpErrorHandler)
840 g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
848 } while (remainLen > 0);
850 OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
853 void CATCPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
856 VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
857 VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
861 if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
863 sendData(endpoint, data, datalen, "ipv6");
865 if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
867 sendData(endpoint, data, datalen, "ipv4");
872 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
874 VERIFY_NON_NULL(info, TAG, "info is NULL");
875 VERIFY_NON_NULL(size, TAG, "size is NULL");
877 return CA_NOT_SUPPORTED;
880 CATCPSessionInfo_t *CAConnectTCPSession(const CAEndpoint_t *endpoint)
882 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
884 // #1. create TCP server object
885 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
888 OIC_LOG(ERROR, TAG, "Out of memory");
891 memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
892 svritem->sep.endpoint.adapter = endpoint->adapter;
893 svritem->sep.endpoint.port = endpoint->port;
894 svritem->sep.endpoint.flags = endpoint->flags;
895 svritem->sep.endpoint.ifindex = endpoint->ifindex;
897 // #2. create the socket and connect to TCP server
898 int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
899 int fd = CATCPCreateSocket(family, svritem);
906 // #3. add TCP connection info to list
908 ca_mutex_lock(g_mutexObjectList);
909 if (caglobals.tcp.svrlist)
911 bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
914 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
917 ca_mutex_unlock(g_mutexObjectList);
921 ca_mutex_unlock(g_mutexObjectList);
925 // pass the connection information to CA Common Layer.
926 if (g_connectionCallback)
928 g_connectionCallback(&(svritem->sep.endpoint), true);
934 CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *svritem, size_t index)
936 VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
938 ca_mutex_lock(g_mutexObjectList);
940 // close the socket and remove TCP connection info in list
941 if (svritem->fd >= 0)
945 u_arraylist_remove(caglobals.tcp.svrlist, index);
946 OICFree(svritem->recvData);
948 // pass the connection information to CA Common Layer.
949 if (g_connectionCallback)
951 g_connectionCallback(&(svritem->sep.endpoint), false);
955 ca_mutex_unlock(g_mutexObjectList);
960 void CATCPDisconnectAll()
962 ca_mutex_lock(g_mutexObjectList);
963 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
965 CATCPSessionInfo_t *svritem = NULL;
966 for (size_t i = 0; i < length; i++)
968 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
969 if (svritem && svritem->fd >= 0)
971 shutdown(svritem->fd, SHUT_RDWR);
973 OICFree(svritem->recvData);
976 u_arraylist_destroy(caglobals.tcp.svrlist);
977 ca_mutex_unlock(g_mutexObjectList);
980 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
982 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
983 VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
985 // get connection info from list
986 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
987 for (size_t i = 0; i < length; i++)
989 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
990 caglobals.tcp.svrlist, i);
996 if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
997 sizeof(svritem->sep.endpoint.addr))
998 && (svritem->sep.endpoint.port == endpoint->port)
999 && (svritem->sep.endpoint.flags & endpoint->flags))
1009 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1011 ca_mutex_lock(g_mutexObjectList);
1013 // check from the last item.
1014 CATCPSessionInfo_t *svritem = NULL;
1015 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1016 for (size_t i = 0; i < length; i++)
1018 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1020 if (svritem && svritem->fd == fd)
1023 ca_mutex_unlock(g_mutexObjectList);
1028 ca_mutex_unlock(g_mutexObjectList);
1033 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1035 OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1037 coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
1038 ((unsigned char *)recvBuffer)[0] >> 4);
1039 size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1041 size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1043 OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%d]", optPaylaodLen);
1044 OIC_LOG_V(DEBUG, TAG, "header length [%d]", headerLen);
1045 OIC_LOG_V(DEBUG, TAG, "total data length [%d]", headerLen + optPaylaodLen);
1047 OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1048 return headerLen + optPaylaodLen;
1051 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1053 g_tcpErrorHandler = errorHandleCallback;