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"
47 #include "ca_adapter_net_tls.h"
51 * Logging tag for module name.
53 #define TAG "OIC_CA_TCP_SERVER"
56 * Maximum CoAP over TCP header length
57 * to know the total data length.
59 #define COAP_MAX_HEADER_SIZE 6
64 #define TLS_HEADER_SIZE 5
67 * Mutex to synchronize device object list.
69 static ca_mutex g_mutexObjectList = NULL;
72 * Conditional mutex to synchronize.
74 static ca_cond g_condObjectList = NULL;
77 * Maintains the callback to be notified when data received from remote device.
79 static CATCPPacketReceivedCallback g_packetReceivedCallback = NULL;
82 * Error callback to update error in TCP.
84 static CATCPErrorHandleCallback g_tcpErrorHandler = NULL;
87 * Connected Callback to pass the connection information to RI.
89 static CATCPConnectionHandleCallback g_connectionCallback = NULL;
91 static CAResult_t CATCPCreateMutex();
92 static void CATCPDestroyMutex();
93 static CAResult_t CATCPCreateCond();
94 static void CATCPDestroyCond();
95 static int CACreateAcceptSocket(int family, CASocket_t *sock);
96 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock);
97 static void CAFindReadyMessage();
98 static void CASelectReturned(fd_set *readFds);
99 static void CAReceiveMessage(int fd);
100 static void CAReceiveHandler(void *data);
101 static int CATCPCreateSocket(int family, CATCPSessionInfo_t *tcpServerInfo);
103 #define CHECKFD(FD) \
104 if (FD > caglobals.tcp.maxfd) \
105 caglobals.tcp.maxfd = FD;
107 #define REALLOC(buffer, length) \
109 unsigned char *tmpBuf = OICRealloc(buffer, length); \
112 OIC_LOG(ERROR, TAG, "out of memory"); \
119 * Read length amount of data from socket fd
120 * Made a few recv calls if required
122 * @param[in] fd - socket
123 * @param[out] item - used to update received message length
124 * @param[out] data - buffer to store data
125 * @param[in] length - length of data required to read
126 * @param[in] flags - additional info about socket
128 #define RECV(fd, item, data, length, flags) \
130 int remain_len = length; \
132 while (remain_len > 0) \
134 len = recv(fd, data + item->len, remain_len, flags); \
135 OIC_LOG_V(DEBUG, TAG, "recv len = %d", len); \
136 OIC_LOG_BUFFER(DEBUG, TAG, data + item->len, len); \
137 if (2 == len && 0 == data[item->len] && 0 == data[item->len + 1]) \
139 OIC_LOG(DEBUG, TAG, "received RESET message. Skip it"); \
144 OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno)); \
149 OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection"); \
157 static void CATCPDestroyMutex()
159 if (g_mutexObjectList)
161 ca_mutex_free(g_mutexObjectList);
162 g_mutexObjectList = NULL;
166 static CAResult_t CATCPCreateMutex()
168 if (!g_mutexObjectList)
170 g_mutexObjectList = ca_mutex_new();
171 if (!g_mutexObjectList)
173 OIC_LOG(ERROR, TAG, "Failed to created mutex!");
174 return CA_STATUS_FAILED;
181 static void CATCPDestroyCond()
183 if (g_condObjectList)
185 ca_cond_free(g_condObjectList);
186 g_condObjectList = NULL;
190 static CAResult_t CATCPCreateCond()
192 if (!g_condObjectList)
194 g_condObjectList = ca_cond_new();
195 if (!g_condObjectList)
197 OIC_LOG(ERROR, TAG, "Failed to created cond!");
198 return CA_STATUS_FAILED;
204 static void CAReceiveHandler(void *data)
207 OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler");
209 while (!caglobals.tcp.terminate)
211 CAFindReadyMessage();
214 ca_mutex_lock(g_mutexObjectList);
215 ca_cond_signal(g_condObjectList);
216 ca_mutex_unlock(g_mutexObjectList);
218 OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
221 static void CAFindReadyMessage()
224 struct timeval timeout = { .tv_sec = caglobals.tcp.selectTimeout };
228 if (-1 != caglobals.tcp.ipv4.fd)
230 FD_SET(caglobals.tcp.ipv4.fd, &readFds);
232 if (-1 != caglobals.tcp.ipv6.fd)
234 FD_SET(caglobals.tcp.ipv6.fd, &readFds);
236 if (-1 != caglobals.tcp.shutdownFds[0])
238 FD_SET(caglobals.tcp.shutdownFds[0], &readFds);
240 if (-1 != caglobals.tcp.connectionFds[0])
242 FD_SET(caglobals.tcp.connectionFds[0], &readFds);
245 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
246 for (size_t i = 0; i < length; i++)
248 CATCPSessionInfo_t *svritem =
249 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
250 if (svritem && 0 <= svritem->fd)
252 FD_SET(svritem->fd, &readFds);
256 int ret = select(caglobals.tcp.maxfd + 1, &readFds, NULL, NULL, &timeout);
258 if (caglobals.tcp.terminate)
260 OIC_LOG_V(DEBUG, TAG, "Packet receiver Stop request received.");
267 OIC_LOG_V(FATAL, TAG, "select error %s", strerror(errno));
272 CASelectReturned(&readFds);
275 static void CASelectReturned(fd_set *readFds)
277 VERIFY_NON_NULL_VOID(readFds, TAG, "readFds is NULL");
279 if (caglobals.tcp.ipv4.fd != -1 && FD_ISSET(caglobals.tcp.ipv4.fd, readFds))
281 CAAcceptConnection(CA_IPV4, &caglobals.tcp.ipv4);
284 else if (caglobals.tcp.ipv6.fd != -1 && FD_ISSET(caglobals.tcp.ipv6.fd, readFds))
286 CAAcceptConnection(CA_IPV6, &caglobals.tcp.ipv6);
289 else if (-1 != caglobals.tcp.connectionFds[0] &&
290 FD_ISSET(caglobals.tcp.connectionFds[0], readFds))
292 // new connection was created from remote device.
293 // exit the function to update read file descriptor.
294 char buf[MAX_ADDR_STR_SIZE_CA] = {0};
295 ssize_t len = read(caglobals.tcp.connectionFds[0], buf, sizeof (buf));
300 OIC_LOG_V(DEBUG, TAG, "Received new connection event with [%s]", buf);
301 FD_CLR(caglobals.tcp.connectionFds[0], readFds);
306 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
307 for (size_t i = 0; i < length; i++)
309 CATCPSessionInfo_t *svritem =
310 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
311 if (svritem && svritem->fd >= 0)
313 if (FD_ISSET(svritem->fd, readFds))
315 CAReceiveMessage(svritem->fd);
316 FD_CLR(svritem->fd, readFds);
323 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock)
325 VERIFY_NON_NULL_VOID(sock, TAG, "sock is NULL");
327 struct sockaddr_storage clientaddr;
328 socklen_t clientlen = sizeof (struct sockaddr_in);
331 clientlen = sizeof(struct sockaddr_in6);
334 int sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen);
337 CATCPSessionInfo_t *svritem =
338 (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
341 OIC_LOG(ERROR, TAG, "Out of memory");
346 svritem->fd = sockfd;
347 svritem->sep.endpoint.flags = flag;
348 CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
349 svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
351 ca_mutex_lock(g_mutexObjectList);
352 bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem);
355 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
358 ca_mutex_unlock(g_mutexObjectList);
361 ca_mutex_unlock(g_mutexObjectList);
368 static bool CAIsTlsMessage(const CATCPSessionInfo_t * recvinfo)
370 if (recvinfo->data == NULL || recvinfo->len == 0)
372 OIC_LOG_V(ERROR, TAG, "%s: null input param", __func__);
376 unsigned char first_byte = recvinfo->data[0];
378 //TLS Plaintext has four types: change_cipher_spec = [14], alert = [15],
379 //handshake = [16], application_data = [17] in HEX
380 const uint8_t tls_head_type[] = {0x14, 0x15, 0x16, 0x17};
383 for (i = 0; i < sizeof(tls_head_type); i++)
385 if(tls_head_type[i] == first_byte)
395 static void CAReceiveMessage(int fd)
397 // #1. get remote device information from file descriptor.
399 CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFD(fd, &index);
402 OIC_LOG(ERROR, TAG, "there is no connection information in list");
406 // #2. allocate memory for message header (CoAP header size because it is bigger)
407 svritem->data = (unsigned char *) OICCalloc(1, COAP_MAX_HEADER_SIZE);
410 OIC_LOG(ERROR, TAG, "out of memory");
414 // #3. read data (assume TLS header) from remote device.
415 RECV(fd, svritem, svritem->data, TLS_HEADER_SIZE, 0);
418 if (CAIsTlsMessage(svritem))
420 // #4.1 get tls body length from tls header. [3][4] bytes are length of tls body in header
421 unsigned int message_length = (unsigned int)((svritem->data[3] << 8) | svritem->data[4]);
422 OIC_LOG_V(DEBUG, TAG, "%s: message_length = %d", __func__, message_length);
424 REALLOC(svritem->data, message_length + TLS_HEADER_SIZE);
426 RECV(fd, svritem, svritem->data, message_length, 0);
428 int ret = CAdecryptTls(&svritem->sep, (uint8_t *)svritem->data, svritem->len);
430 OIC_LOG_V(DEBUG, TAG, "%s: CAdecryptTls returned %d", __func__, ret);
436 // #4.2 Seems CoAP data received. read full coap header.
437 coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(svritem->data[0] >> 4);
439 size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
441 if (svritem->len < headerLen)
443 // read required bytes to have full CoAP header
444 // usually it is 1 bytes (COAP_MAX_HEADER_SIZE - TLS_HEADER_SIZE)
445 RECV(fd, svritem, svritem->data, headerLen - svritem->len, 0);
448 // #4.3 Calculate CoAP message length and read it
449 size_t total_length = CAGetTotalLengthFromHeader(svritem->data);
450 REALLOC(svritem->data, total_length);
452 RECV(fd, svritem, svritem->data, total_length - svritem->len, 0);
454 // #4.4. pass the received data information to upper layer.
455 if (g_packetReceivedCallback)
457 svritem->sep.endpoint.adapter = CA_ADAPTER_TCP;
458 g_packetReceivedCallback(&svritem->sep, svritem->data, svritem->len);
464 CADisconnectTCPSession(svritem, index);
467 // initialize data info to receive next message.
468 OICFree(svritem->data);
469 svritem->data = NULL;
475 static void CAWakeUpForReadFdsUpdate(const char *host)
477 if (caglobals.tcp.connectionFds[1] != -1)
482 len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
483 } while ((len == -1) && (errno == EINTR));
485 if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
487 OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
492 static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port,
493 struct sockaddr_storage *sockaddr)
495 struct addrinfo *addrs = NULL;
496 struct addrinfo hints = { .ai_family = family,
497 .ai_protocol = IPPROTO_TCP,
498 .ai_socktype = SOCK_STREAM,
499 .ai_flags = AI_NUMERICHOST };
501 int r = getaddrinfo(host, NULL, &hints, &addrs);
506 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: errno %s", strerror(errno));
510 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: %s", gai_strerror(r));
513 return CA_STATUS_FAILED;
515 // assumption: in this case, getaddrinfo will only return one addrinfo
516 // or first is the one we want.
517 if (addrs[0].ai_family == AF_INET6)
519 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6));
520 ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port);
524 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in));
525 ((struct sockaddr_in *)sockaddr)->sin_port = htons(port);
531 static int CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
533 // #1. create tcp socket.
534 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
537 OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
541 // #2. convert address from string to binary.
542 struct sockaddr_storage sa = { .ss_family = family };
543 CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr,
544 svritem->sep.endpoint.port, &sa);
545 if (CA_STATUS_OK != res)
551 // #3. set socket length.
552 socklen_t socklen = 0;
553 if (sa.ss_family == AF_INET6)
555 struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
556 if (!sock6->sin6_scope_id)
558 sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
560 socklen = sizeof(struct sockaddr_in6);
564 socklen = sizeof(struct sockaddr_in);
567 // #4. connect to remote server device.
568 if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
570 OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
575 OIC_LOG(DEBUG, TAG, "connect socket success");
576 CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
580 static int CACreateAcceptSocket(int family, CASocket_t *sock)
582 VERIFY_NON_NULL_RET(sock, TAG, "sock", -1);
586 OIC_LOG(DEBUG, TAG, "accept socket created already");
590 socklen_t socklen = 0;
591 struct sockaddr_storage server = { .ss_family = family };
593 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
596 OIC_LOG(ERROR, TAG, "Failed to create socket");
600 if (family == AF_INET6)
602 // the socket is re‐stricted to sending and receiving IPv6 packets only.
604 if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
606 OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
609 ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port);
610 socklen = sizeof (struct sockaddr_in6);
614 ((struct sockaddr_in *)&server)->sin_port = htons(sock->port);
615 socklen = sizeof (struct sockaddr_in);
619 if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
621 OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
625 if (-1 == bind(fd, (struct sockaddr *)&server, socklen))
627 OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
631 if (listen(fd, caglobals.tcp.listenBacklog) != 0)
633 OIC_LOG(ERROR, TAG, "listen() error");
637 if (!sock->port) // return the assigned port
639 if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen))
641 OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
644 sock->port = ntohs(family == AF_INET6 ?
645 ((struct sockaddr_in6 *)&server)->sin6_port :
646 ((struct sockaddr_in *)&server)->sin_port);
659 static void CAInitializePipe(int *fds)
664 ret = fcntl(fds[0], F_GETFD);
667 ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
671 ret = fcntl(fds[1], F_GETFD);
675 ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
685 OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
690 #define NEWSOCKET(FAMILY, NAME) \
691 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
692 if (caglobals.tcp.NAME.fd == -1) \
694 caglobals.tcp.NAME.port = 0; \
695 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
697 CHECKFD(caglobals.tcp.NAME.fd);
699 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
701 if (caglobals.tcp.started)
706 if (!caglobals.tcp.ipv4tcpenabled)
708 caglobals.tcp.ipv4tcpenabled = true; // only needed to run CA tests
710 if (!caglobals.tcp.ipv6tcpenabled)
712 caglobals.tcp.ipv6tcpenabled = true; // only needed to run CA tests
715 CAResult_t res = CATCPCreateMutex();
716 if (CA_STATUS_OK == res)
718 res = CATCPCreateCond();
720 if (CA_STATUS_OK != res)
722 OIC_LOG(ERROR, TAG, "failed to create mutex/cond");
726 ca_mutex_lock(g_mutexObjectList);
727 if (!caglobals.tcp.svrlist)
729 caglobals.tcp.svrlist = u_arraylist_create();
731 ca_mutex_unlock(g_mutexObjectList);
733 if (caglobals.server)
735 NEWSOCKET(AF_INET, ipv4);
736 NEWSOCKET(AF_INET6, ipv6);
737 OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
738 caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
739 OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
740 caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
743 // create pipe for fast shutdown
744 CAInitializePipe(caglobals.tcp.shutdownFds);
745 CHECKFD(caglobals.tcp.shutdownFds[0]);
746 CHECKFD(caglobals.tcp.shutdownFds[1]);
748 // create pipe for connection event
749 CAInitializePipe(caglobals.tcp.connectionFds);
750 CHECKFD(caglobals.tcp.connectionFds[0]);
751 CHECKFD(caglobals.tcp.connectionFds[1]);
753 caglobals.tcp.terminate = false;
754 res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
755 if (CA_STATUS_OK != res)
757 OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
760 OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");
762 caglobals.tcp.started = true;
766 void CATCPStopServer()
769 ca_mutex_lock(g_mutexObjectList);
771 // set terminate flag
772 caglobals.tcp.terminate = true;
774 if (caglobals.tcp.shutdownFds[1] != -1)
776 close(caglobals.tcp.shutdownFds[1]);
777 // receive thread will stop immediately
780 if (caglobals.tcp.connectionFds[1] != -1)
782 close(caglobals.tcp.connectionFds[1]);
785 if (caglobals.tcp.started)
787 ca_cond_wait(g_condObjectList, g_mutexObjectList);
789 caglobals.tcp.started = false;
792 ca_mutex_unlock(g_mutexObjectList);
794 if (-1 != caglobals.tcp.ipv4.fd)
796 close(caglobals.tcp.ipv4.fd);
797 caglobals.tcp.ipv4.fd = -1;
800 if (-1 != caglobals.tcp.ipv6.fd)
802 close(caglobals.tcp.ipv6.fd);
803 caglobals.tcp.ipv6.fd = -1;
806 CATCPDisconnectAll();
811 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
813 g_packetReceivedCallback = callback;
816 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
818 g_connectionCallback = connHandler;
821 static void sendData(const CAEndpoint_t *endpoint, const void *data,
822 size_t dlen, const char *fam)
824 // #1. get TCP Server object from list
826 CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
829 // if there is no connection info, connect to TCP Server
830 svritem = CAConnectTCPSession(endpoint);
833 OIC_LOG(ERROR, TAG, "Failed to create TCP server object");
834 if (g_tcpErrorHandler)
836 g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
842 // #2. check connection state
845 // if file descriptor value is wrong, remove TCP Server info from list
846 OIC_LOG(ERROR, TAG, "Failed to connect to TCP server");
847 CADisconnectTCPSession(svritem, index);
848 if (g_tcpErrorHandler)
850 g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
855 // #4. send data to TCP Server
856 ssize_t remainLen = dlen;
859 ssize_t len = send(svritem->fd, data, remainLen, 0);
862 if (EWOULDBLOCK != errno)
864 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
865 if (g_tcpErrorHandler)
867 g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
875 } while (remainLen > 0);
877 OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
880 void CATCPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
883 VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
884 VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");
888 if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
890 sendData(endpoint, data, datalen, "ipv6");
892 if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
894 sendData(endpoint, data, datalen, "ipv4");
899 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
901 VERIFY_NON_NULL(info, TAG, "info is NULL");
902 VERIFY_NON_NULL(size, TAG, "size is NULL");
904 return CA_NOT_SUPPORTED;
907 CATCPSessionInfo_t *CAConnectTCPSession(const CAEndpoint_t *endpoint)
909 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
911 // #1. create TCP server object
912 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
915 OIC_LOG(ERROR, TAG, "Out of memory");
918 memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
919 svritem->sep.endpoint.adapter = endpoint->adapter;
920 svritem->sep.endpoint.port = endpoint->port;
921 svritem->sep.endpoint.flags = endpoint->flags;
922 svritem->sep.endpoint.ifindex = endpoint->ifindex;
924 // #2. create the socket and connect to TCP server
925 int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
926 int fd = CATCPCreateSocket(family, svritem);
933 // #3. add TCP connection info to list
935 ca_mutex_lock(g_mutexObjectList);
936 if (caglobals.tcp.svrlist)
938 bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
941 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
944 ca_mutex_unlock(g_mutexObjectList);
948 ca_mutex_unlock(g_mutexObjectList);
952 // pass the connection information to CA Common Layer.
953 if (g_connectionCallback)
955 g_connectionCallback(&(svritem->sep.endpoint), true);
961 CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *svritem, size_t index)
963 VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
965 ca_mutex_lock(g_mutexObjectList);
967 // close the socket and remove TCP connection info in list
968 if (svritem->fd >= 0)
972 u_arraylist_remove(caglobals.tcp.svrlist, index);
973 OICFree(svritem->data);
974 svritem->data = NULL;
976 // pass the connection information to CA Common Layer.
977 if (g_connectionCallback)
979 g_connectionCallback(&(svritem->sep.endpoint), false);
983 ca_mutex_unlock(g_mutexObjectList);
988 void CATCPDisconnectAll()
990 ca_mutex_lock(g_mutexObjectList);
991 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
993 CATCPSessionInfo_t *svritem = NULL;
994 for (size_t i = 0; i < length; i++)
996 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
997 if (svritem && svritem->fd >= 0)
999 shutdown(svritem->fd, SHUT_RDWR);
1002 OICFree(svritem->data);
1003 svritem->data = NULL;
1006 u_arraylist_destroy(caglobals.tcp.svrlist);
1007 ca_mutex_unlock(g_mutexObjectList);
1010 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
1012 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1013 VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
1015 // get connection info from list
1016 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1017 for (size_t i = 0; i < length; i++)
1019 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1020 caglobals.tcp.svrlist, i);
1026 if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1027 sizeof(svritem->sep.endpoint.addr))
1028 && (svritem->sep.endpoint.port == endpoint->port)
1029 && (svritem->sep.endpoint.flags & endpoint->flags))
1039 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1041 ca_mutex_lock(g_mutexObjectList);
1043 // check from the last item.
1044 CATCPSessionInfo_t *svritem = NULL;
1045 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1046 for (size_t i = 0; i < length; i++)
1048 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1050 if (svritem && svritem->fd == fd)
1053 ca_mutex_unlock(g_mutexObjectList);
1058 ca_mutex_unlock(g_mutexObjectList);
1063 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1065 OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1067 coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(
1068 ((unsigned char *)recvBuffer)[0] >> 4);
1069 size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1071 size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1073 OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%zu]", optPaylaodLen);
1074 OIC_LOG_V(DEBUG, TAG, "header length [%zu]", headerLen);
1075 OIC_LOG_V(DEBUG, TAG, "total data length [%zu]", headerLen + optPaylaodLen);
1077 OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1078 return headerLen + optPaylaodLen;
1081 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1083 g_tcpErrorHandler = errorHandleCallback;