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/ioctl.h>
24 #if defined(__TIZEN__)
28 #include <tinyara/config.h>
36 #include <arpa/inet.h>
37 #include <netinet/in.h>
38 #include <netinet/tcp.h>
43 #include <sys/socket.h>
44 #include <netinet/in.h>
48 #include "catcpinterface.h"
49 #include "caipnwmonitor.h"
51 #include "caadapterutils.h"
53 #include "oic_malloc.h"
54 #include "oic_string.h"
57 #include "ca_adapter_net_ssl.h"
61 * Logging tag for module name.
63 //#define TAG "OIC_CA_TCP_SERVER"
64 #define TAG TCP_SERVER_TAG
67 * Maximum CoAP over TCP header length
68 * to know the total data length.
70 #define COAP_MAX_HEADER_SIZE 6
75 #define TLS_HEADER_SIZE 5
78 * Max Connection Counts.
80 #define MAX_CONNECTION_COUNTS 500
82 #define COAP_TCP_MAX_BUFFER_CHUNK_SIZE 65530 //64kb - 6 (coap+tcp max header size)
84 #define MILLISECONDS_PER_SECOND (1000)
89 static ca_thread_pool_t g_threadPool = NULL;
94 static uint32_t g_taskId = 0;
97 * Mutex to synchronize device object list.
99 static oc_mutex g_mutexObjectList = NULL;
102 * Conditional mutex to synchronize.
104 static oc_cond g_condObjectList = NULL;
107 * Mutex to synchronize send.
109 static oc_mutex g_mutexSend = NULL;
112 * Conditional mutex to synchronize send.
114 static oc_cond g_condSend = NULL;
117 * Maintains the callback to be notified when data received from remote device.
119 static CATCPPacketReceivedCallback g_packetReceivedCallback = NULL;
122 * Error callback to update error in TCP.
124 static CATCPErrorHandleCallback g_tcpErrorHandler = NULL;
127 * Connected Callback to pass the connection information to RI.
129 static CATCPConnectionHandleCallback g_connectionCallback = NULL;
132 * Error code to hold the errno(Timeout, Destination unreachable, etc) when send/recv fails.
133 * Main purpose is to hold the reason for connection drop when keep-alive is in use.
134 * To indicate normal disconnection, 0 will be assigned.
136 static int g_lastErrorCode;
138 static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock);
139 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock);
140 static void CAFindReadyMessage();
141 static void CAPollReturned(struct pollfd *readFds, size_t size);
142 static void CAReceiveMessage(int fd);
143 static void CAReceiveHandler(void *data);
144 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem);
145 static void CATCPInitializeSocket();
146 static CATCPSessionInfo_t *CAGetSessionInfoFromFDAsOwner(int fd, size_t *index);
148 #if defined(__TIZEN__)
149 static char g_cloudproxyUri[CA_MAX_URI_LENGTH];
151 static char g_interfaceName[CA_MAX_INTERFACE_NAME_LEN];
153 CAResult_t CASetCloudAddressForProxy(const char *uri)
156 memset(g_cloudproxyUri, '\0', sizeof (g_cloudproxyUri));
158 OICStrcpy(g_cloudproxyUri, sizeof (g_cloudproxyUri), uri);
162 const char *CAGetCloudAddressForProxy()
164 if (g_cloudproxyUri[0] == '\0')
166 return g_cloudproxyUri;
169 CAResult_t CASetTCPServerSocketBindIP(const char* ifname)
171 CAResult_t res = CA_STATUS_OK;
173 VERIFY_NON_NULL_RET(ifname, TAG, "Interface name is NULL", CA_STATUS_INVALID_PARAM);
175 OIC_LOG(DEBUG, TAG, "Setting Socket Bind");
176 caglobals.tcp.bindenabled = true;
177 OICStrcpy(g_interfaceName, sizeof (g_interfaceName), ifname);
179 OIC_LOG(DEBUG, TAG, "Not supported!");
180 res = CA_NOT_SUPPORTED;
186 #define MAX_TCP_SOCK_COUNT 4
188 #define CLOSE_SOCKET(TYPE) \
189 if (caglobals.tcp.TYPE.fd != OC_INVALID_SOCKET) \
191 close(caglobals.tcp.TYPE.fd); \
192 caglobals.tcp.TYPE.fd = OC_INVALID_SOCKET; \
195 #define CA_FD_SET(TYPE, FDS, COUNT) \
196 FDS[COUNT].fd = caglobals.tcp.TYPE.fd; \
197 FDS[COUNT].events = POLLIN;
199 void CATCPDestroyMutex()
201 if (g_mutexObjectList)
203 oc_mutex_free(g_mutexObjectList);
204 g_mutexObjectList = NULL;
208 CAResult_t CATCPCreateMutex()
210 if (!g_mutexObjectList)
212 g_mutexObjectList = oc_mutex_new_recursive();
213 if (!g_mutexObjectList)
215 OIC_LOG(ERROR, TAG, "Failed to create mutex!");
216 return CA_STATUS_FAILED;
223 void CATCPDestroyCond()
225 if (g_condObjectList)
227 oc_cond_free(g_condObjectList);
228 g_condObjectList = NULL;
232 CAResult_t CATCPCreateCond()
234 if (!g_condObjectList)
236 g_condObjectList = oc_cond_new();
237 if (!g_condObjectList)
239 OIC_LOG(ERROR, TAG, "Failed to create cond!");
240 return CA_STATUS_FAILED;
246 void CATCPDestroySendMutex()
250 oc_mutex_free(g_mutexSend);
255 CAResult_t CATCPCreateSendMutex()
259 g_mutexSend = oc_mutex_new();
262 OIC_LOG(ERROR, TAG, "Failed to create send mutex!");
263 return CA_STATUS_FAILED;
270 void CATCPDestroySendCond()
274 oc_cond_free(g_condSend);
279 CAResult_t CATCPCreateSendCond()
283 g_condSend = oc_cond_new();
286 OIC_LOG(ERROR, TAG, "Failed to create send cond!");
287 return CA_STATUS_FAILED;
293 static void CAReceiveHandler(void *data)
296 OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler");
300 oc_mutex_lock(g_mutexObjectList);
301 if (caglobals.tcp.terminate)
303 oc_mutex_unlock(g_mutexObjectList);
306 oc_mutex_unlock(g_mutexObjectList);
307 CAFindReadyMessage();
310 oc_mutex_lock(g_mutexObjectList);
311 oc_cond_signal(g_condObjectList);
312 oc_mutex_unlock(g_mutexObjectList);
314 OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
317 static void CAFindReadyMessage()
319 int timeout = (caglobals.tcp.selectTimeout * 1000);
322 oc_mutex_lock(g_mutexObjectList);
323 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
325 // Consider 4 tcp sockets(ipv4, ipv4s, ipv6, ipv6s) + 1 connection fd + all sockets in svrlist
326 struct pollfd *readFds = (struct pollfd *)OICCalloc(MAX_TCP_SOCK_COUNT + 1 + length, sizeof(struct pollfd));
329 OIC_LOG_V(ERROR, TAG, "Failed to allocate memory!");
330 oc_mutex_unlock(g_mutexObjectList);
335 CA_FD_SET(ipv4, readFds, counter);
337 CA_FD_SET(ipv4s, readFds, counter);
339 CA_FD_SET(ipv6, readFds, counter);
341 CA_FD_SET(ipv6s, readFds, counter);
345 readFds[counter].fd = caglobals.tcp.connectionFds[0];
346 readFds[counter].events = POLLIN;
349 // All sockets in svrlist
350 for (size_t i = 0; i < length; i++)
352 CATCPSessionInfo_t *svritem =
353 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
354 if (svritem && 0 <= svritem->fd && CONNECTED == svritem->state)
356 readFds[counter].fd = svritem->fd;
357 readFds[counter].events = POLLIN;
361 oc_mutex_unlock(g_mutexObjectList);
362 int ret = poll(readFds, counter, timeout);
364 oc_mutex_lock(g_mutexObjectList);
365 if (caglobals.tcp.terminate)
367 OIC_LOG_V(INFO, TAG, "Packet receiver Stop request received.");
368 oc_mutex_unlock(g_mutexObjectList);
372 oc_mutex_unlock(g_mutexObjectList);
376 CAPollReturned(readFds, counter);
380 usleep(1000); /* some of the fields are not set by kernel on repeatedly calling
381 poll.Applying a sleep will solve this by providing a delay between
382 each subsequent poll system call */
386 OIC_LOG_V(FATAL, TAG, "poll error %s", strerror(errno));
392 static void CAPollReturned(struct pollfd *readFds, size_t size)
394 VERIFY_NON_NULL_VOID(readFds, TAG, "readFds is NULL");
396 if (caglobals.tcp.ipv4.fd != -1 && readFds[0].revents == POLLIN)
398 CAAcceptConnection(CA_IPV4, &caglobals.tcp.ipv4);
401 else if (caglobals.tcp.ipv4s.fd != -1 && readFds[1].revents == POLLIN)
403 CAAcceptConnection(CA_IPV4 | CA_SECURE, &caglobals.tcp.ipv4s);
406 else if (caglobals.tcp.ipv6.fd != -1 && readFds[2].revents == POLLIN)
408 CAAcceptConnection(CA_IPV6, &caglobals.tcp.ipv6);
411 else if (caglobals.tcp.ipv6s.fd != -1 && readFds[3].revents == POLLIN)
413 CAAcceptConnection(CA_IPV6 | CA_SECURE, &caglobals.tcp.ipv6s);
416 else if (-1 != caglobals.tcp.connectionFds[0] && readFds[4].revents != 0)
418 // new connection was created from remote device.
419 // exit the function to update read file descriptor.
420 char buf[MAX_ADDR_STR_SIZE_CA] = {0};
421 ssize_t len = read(caglobals.tcp.connectionFds[0], buf, sizeof (buf));
426 OIC_LOG_V(DEBUG, TAG, "Received new connection event with [%s]", buf);
431 int *readFDList = NULL;
432 size_t readFDListSize = 0;
434 oc_mutex_lock(g_mutexObjectList);
435 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
437 readFDList = (int*) OICCalloc(length, sizeof(int));
438 if (NULL == readFDList)
440 OIC_LOG_V(ERROR, TAG, "Failed to allocate memory!");
441 oc_mutex_unlock(g_mutexObjectList);
445 for (size_t i = 0; i < length; i++)
447 CATCPSessionInfo_t *svritem =
448 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
449 if (svritem && svritem->fd >= 0)
454 if (svritem->fd == readFds[j].fd)
461 if (j < size && readFds[j].revents != 0)
463 readFDList[readFDListSize++] = svritem->fd;
467 oc_mutex_unlock(g_mutexObjectList);
469 // Read incomming messages from fds
470 for (size_t i = 0; i < readFDListSize; i++)
472 CAReceiveMessage(readFDList[i]);
479 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock)
481 OIC_LOG_V(INFO, TAG, "In %s", __func__);
482 VERIFY_NON_NULL_VOID(sock, TAG, "sock is NULL");
484 if (MAX_CONNECTION_COUNTS == u_arraylist_length(caglobals.tcp.svrlist))
486 OIC_LOG_V(INFO, TAG, "Exceeding the max connection counts limit, close listening port");
488 sock->fd = OC_INVALID_SOCKET;
492 struct sockaddr_storage clientaddr;
493 socklen_t clientlen = sizeof (struct sockaddr_in);
496 clientlen = sizeof(struct sockaddr_in6);
499 CASocketFd_t sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen);
500 if (OC_INVALID_SOCKET != sockfd)
502 CATCPSessionInfo_t *svritem =
503 (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
506 OIC_LOG(ERROR, TAG, "Out of memory");
511 svritem->fd = sockfd;
512 svritem->sep.endpoint.flags = flag;
513 svritem->sep.endpoint.adapter = CA_ADAPTER_TCP;
514 svritem->state = CONNECTED;
515 svritem->isClient = false;
516 CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
517 svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
519 // Allocate message buffer
520 svritem->tlsdata = (unsigned char*) OICCalloc(TLS_DATA_MAX_SIZE, sizeof(unsigned char));
521 if (!svritem->tlsdata)
523 OIC_LOG(ERROR, TAG, "Out of memory");
529 oc_mutex_lock(g_mutexObjectList);
530 bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem);
533 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
535 OICFree(svritem->tlsdata);
537 oc_mutex_unlock(g_mutexObjectList);
540 oc_mutex_unlock(g_mutexObjectList);
542 // pass the connection information to CA Common Layer.
543 if (g_connectionCallback)
545 g_connectionCallback(&(svritem->sep.endpoint), true, svritem->isClient);
548 OIC_LOG_V(INFO, TAG, "Out %s", __func__);
552 * Clean socket state data
554 * @param[in/out] item - socket state data
556 void CACleanData(CATCPSessionInfo_t *svritem)
560 OICFree(svritem->data);
561 svritem->data = NULL;
566 svritem->totalLen = 0;
568 svritem->protocol = UNKNOWN;
573 * Construct CoAP header and payload from buffer
575 * @param[in] svritem - used socket, buffer, current received message length and protocol
576 * @param[in/out] data - data buffer, this value is updated as data is copied to svritem
577 * @param[in/out] dataLength - length of data, this value decreased as data is copied to svritem
578 * @return - CA_STATUS_OK or appropriate error code
580 CAResult_t CAConstructCoAP(CATCPSessionInfo_t *svritem, unsigned char **data,
583 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
585 if (NULL == svritem || NULL == data || NULL == dataLength)
587 OIC_LOG(ERROR, TAG, "Invalid input parameter(NULL)");
588 return CA_STATUS_INVALID_PARAM;
591 unsigned char *inBuffer = *data;
592 size_t inLen = *dataLength;
593 OIC_LOG_V(DEBUG, TAG, "before-datalength : %zd", *dataLength);
595 if (NULL == svritem->data && inLen > 0)
597 // allocate memory for message header (CoAP header size because it is bigger)
598 svritem->data = (unsigned char *) OICCalloc(1, COAP_MAX_HEADER_SIZE);
599 if (NULL == svritem->data)
601 OIC_LOG(ERROR, TAG, "OICCalloc - out of memory");
602 return CA_MEMORY_ALLOC_FAILED;
605 // copy 1 byte to parse coap header length
606 memcpy(svritem->data, inBuffer, 1);
608 svritem->bufLen = COAP_MAX_HEADER_SIZE;
613 //if not enough data received - read them on next CAFillHeader() call
619 //if enough data received - parse header
620 svritem->protocol = COAP;
622 //seems CoAP data received. read full coap header.
623 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(svritem->data[0] >> 4);
624 size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
628 if (svritem->len < headerLen)
630 copyLen = headerLen - svritem->len;
636 //read required bytes to have full CoAP header
637 memcpy(svritem->data + svritem->len, inBuffer, copyLen);
638 svritem->len += copyLen;
642 //if not enough data received - read them on next CAFillHeader() call
643 if (svritem->len < headerLen)
647 OIC_LOG(DEBUG, TAG, "CoAP header received partially. Wait for rest header data");
651 //calculate CoAP message length
652 svritem->totalLen = CAGetTotalLengthFromHeader(svritem->data);
658 // Calculate length of data to be copied.
659 copyLen = svritem->totalLen - svritem->len;
665 // Is buffer not big enough for remaining data ?
666 if (svritem->len + copyLen > svritem->bufLen)
668 // Resize buffer to accommodate enough space
669 size_t extLen = svritem->totalLen - svritem->bufLen;
670 if (extLen > COAP_TCP_MAX_BUFFER_CHUNK_SIZE)
672 extLen = COAP_TCP_MAX_BUFFER_CHUNK_SIZE;
675 // Allocate required memory
676 unsigned char *buffer = OICRealloc(svritem->data, svritem->bufLen + extLen);
679 OIC_LOG(ERROR, TAG, "OICRealloc - out of memory");
680 return CA_MEMORY_ALLOC_FAILED;
683 svritem->data = buffer;
684 svritem->bufLen += extLen;
687 // Read required bytes to have full CoAP payload
688 memcpy(svritem->data + svritem->len, inBuffer, copyLen);
689 svritem->len += copyLen;
697 OIC_LOG_V(DEBUG, TAG, "after-datalength : %zd", *dataLength);
698 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
702 static void CAReceiveMessage(int fd)
704 CAResult_t res = CA_STATUS_OK;
706 oc_mutex_lock(g_mutexObjectList);
708 //get remote device information from file descriptor.
710 CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFDAsOwner(fd, &index);
713 OIC_LOG(ERROR, TAG, "there is no connection information in list");
714 oc_mutex_unlock(g_mutexObjectList);
718 CASecureEndpoint_t peerEP = svritem->sep;
720 if (svritem->sep.endpoint.flags & CA_SECURE) // Secure connection
722 svritem->protocol = TLS;
726 size_t tlsLength = 0;
728 if (TLS_HEADER_SIZE > svritem->tlsLen)
730 nbRead = TLS_HEADER_SIZE - svritem->tlsLen;
734 //[3][4] bytes in tls header are tls payload length
735 tlsLength = TLS_HEADER_SIZE +
736 (size_t)((svritem->tlsdata[3] << 8) | svritem->tlsdata[4]);
737 OIC_LOG_V(DEBUG, TAG, "total tls length = %zd", tlsLength);
738 if (tlsLength > TLS_DATA_MAX_SIZE)
740 OIC_LOG_V(ERROR, TAG, "total tls length is too big (buffer size : %u)",
742 oc_mutex_unlock(g_mutexObjectList);
743 CATCPDisconnectSession(&peerEP.endpoint);
746 nbRead = tlsLength - svritem->tlsLen;
749 len = recv(fd, svritem->tlsdata + svritem->tlsLen, nbRead, 0);
752 g_lastErrorCode = errno;
753 OIC_LOG_V(DEBUG, TAG, "Set g_lastErrorCode to %s", strerror(g_lastErrorCode));
754 OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(g_lastErrorCode));
755 res = CA_RECEIVE_FAILED;
760 OIC_LOG(DEBUG, TAG, "Set g_lastErrorCode to 0");
761 OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
762 svritem->state = DISCONNECTED;
763 res = CA_DESTINATION_DISCONNECTED;
767 svritem->tlsLen += len;
768 OIC_LOG_V(DEBUG, TAG, "nb_read : %zd bytes , recv() : %d bytes, svritem->tlsLen : %zd bytes",
769 nbRead, len, svritem->tlsLen);
770 if (tlsLength > 0 && tlsLength == svritem->tlsLen)
772 // When successfully read data - pass them to callback.
773 // Dont invoke callback locking mutex
774 unsigned char *mesBuf = svritem->tlsdata;
775 size_t mesBufLen = svritem->tlsLen;
776 svritem->tlsdata = NULL;
777 oc_mutex_unlock(g_mutexObjectList);
779 res = CAdecryptSsl(&peerEP, (uint8_t *)mesBuf, mesBufLen);
780 OIC_LOG_V(INFO, TAG, "%s: CAdecryptSsl returned %d", __func__, res);
782 // Check for the svritem and reset buffer
783 oc_mutex_lock(g_mutexObjectList);
784 svritem = CAGetSessionInfoFromFDAsOwner(fd, &index);
787 svritem->tlsdata = mesBuf;
792 // svritem does not exist, thus free the message buffer
793 OIC_LOG(ERROR, TAG, "svritem not found. Freeing message buffer!");
800 else // Non-Secure connection
802 svritem->protocol = COAP;
804 // svritem->tlsdata can also be used as receiving buffer in case of raw tcp
805 len = recv(fd, svritem->tlsdata, TLS_DATA_MAX_SIZE, 0);
808 g_lastErrorCode = errno;
809 OIC_LOG_V(DEBUG, TAG, "Set g_lastErrorCode to %s", strerror(g_lastErrorCode));
810 OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(g_lastErrorCode));
811 res = CA_RECEIVE_FAILED;
816 OIC_LOG_V(DEBUG, TAG, "Set g_lastErrorCode to 0");
817 OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
818 res = CA_DESTINATION_DISCONNECTED;
822 //when successfully read data - pass them to callback.
823 OIC_LOG_V(DEBUG, TAG, "recv() : %d bytes", len);
824 if (g_packetReceivedCallback)
826 // Dont invoke callback locking mutex
827 unsigned char *mesBuf = svritem->tlsdata;
828 svritem->tlsdata = NULL;
829 oc_mutex_unlock(g_mutexObjectList);
831 res = g_packetReceivedCallback(&peerEP, mesBuf, len);
833 // Check for the svritem and reset buffer
834 oc_mutex_lock(g_mutexObjectList);
835 svritem = CAGetSessionInfoFromFDAsOwner(fd, &index);
838 svritem->tlsdata = mesBuf;
843 // svritem does not exist, thus free the message buffer
844 OIC_LOG(ERROR, TAG, "svritem not found. Freeing message buffer!");
851 oc_mutex_unlock(g_mutexObjectList);
853 if (res != CA_STATUS_OK)
855 CATCPDisconnectSession(&peerEP.endpoint);
859 static ssize_t CAWakeUpForReadFdsUpdate(const char *host)
861 if (caglobals.tcp.connectionFds[1] != -1)
866 len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
867 } while ((len == -1) && (errno == EINTR));
869 if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
871 OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
878 static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port,
879 struct sockaddr_storage *sockaddr)
881 struct addrinfo *addrs = NULL;
882 struct addrinfo hints = { .ai_family = family,
883 .ai_protocol = IPPROTO_TCP,
884 .ai_socktype = SOCK_STREAM,
885 .ai_flags = AI_NUMERICHOST };
887 int r = getaddrinfo(host, NULL, &hints, &addrs);
892 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: errno %s", strerror(errno));
896 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: %s", gai_strerror(r));
899 return CA_STATUS_FAILED;
901 // assumption: in this case, getaddrinfo will only return one addrinfo
902 // or first is the one we want.
903 if (addrs[0].ai_family == AF_INET6)
905 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6));
906 ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port);
910 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in));
911 ((struct sockaddr_in *)sockaddr)->sin_port = htons(port);
917 #if defined(__TIZEN__)
918 static char * CATCPGetInterfaceAddr()
920 struct ifaddrs *ifaddr, *ifa;
922 char *host = (uint8_t *)OICMalloc(NI_MAXHOST);
924 if (getifaddrs(&ifaddr) == -1)
926 OIC_LOG_V(ERROR, TAG, "getifaddrs failed: errno %s", strerror(errno));
931 for (ifa = ifaddr, n = 0; ifa != NULL; ifa = ifa->ifa_next, n++)
933 if (ifa->ifa_addr == NULL)
936 family = ifa->ifa_addr->sa_family;
937 OIC_LOG_V(DEBUG, TAG,"Interface name: %s",ifa->ifa_name);
939 if ((strncmp(g_interfaceName,ifa->ifa_name,strlen(ifa->ifa_name))==0)
940 && (family == AF_INET || family == AF_INET6))
942 s = getnameinfo(ifa->ifa_addr, (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6),
943 host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
946 OIC_LOG_V(ERROR, TAG, "getnameinfo failed: errno %s", strerror(errno));
952 OIC_LOG_V(DEBUG, TAG, "Interface address: %s", host);
960 OIC_LOG(ERROR, TAG, "Interface address not found");
965 #if defined(__TIZEN__)
966 static int CAGetHTTPStatusCode(char * response) {
967 char *resp, *code_plus, *ptrSave;
970 resp = strdup(response);
971 strtok_r(resp, " ", &ptrSave); /* skip HTTP version */
972 code_plus = strtok_r(NULL, " ", &ptrSave);
974 ret = code_plus ? atoi(code_plus) : -1;
980 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
982 VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
984 OIC_LOG_V(INFO, TAG, "try to connect with [%s:%u]",
985 svritem->sep.endpoint.addr, svritem->sep.endpoint.port);
987 // #1. create tcp socket.
988 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
991 OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
992 return CA_SOCKET_OPERATION_FAILED;
996 // #2. convert address from string to binary.
997 struct sockaddr_storage sa = { .ss_family = family };
998 CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr,
999 svritem->sep.endpoint.port, &sa);
1000 if (CA_STATUS_OK != res)
1002 OIC_LOG(ERROR, TAG, "convert name to sockaddr failed");
1003 return CA_SOCKET_OPERATION_FAILED;
1006 // #3. set socket length.
1007 socklen_t socklen = 0;
1008 if (sa.ss_family == AF_INET6)
1010 struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
1011 if (!sock6->sin6_scope_id)
1013 sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
1015 socklen = sizeof(struct sockaddr_in6);
1019 socklen = sizeof(struct sockaddr_in);
1022 #if defined(__TIZEN__)
1023 if (caglobals.tcp.bindenabled)
1025 char *host_address = CATCPGetInterfaceAddr();
1028 if (sa.ss_family == AF_INET)
1030 struct sockaddr_in client;
1031 memset(&client, 0x00, sizeof(client));
1032 client.sin_family = AF_INET;
1033 inet_pton(AF_INET, host_address, &(client.sin_addr.s_addr));
1034 if (-1 == bind(fd, (struct sockaddr *)&client, socklen))
1036 OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
1037 OICFree(host_address);
1038 return CA_SOCKET_OPERATION_FAILED;
1043 struct sockaddr_in6 client6;
1044 memset(&client6, 0x00, sizeof(client6));
1045 client6.sin6_family = AF_INET6;
1046 inet_pton(AF_INET6, host_address, &client6.sin6_addr.s6_addr);
1047 if (-1 == bind(fd, (struct sockaddr *)&client6, socklen))
1049 OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
1050 OICFree(host_address);
1051 return CA_SOCKET_OPERATION_FAILED;
1054 OICFree(host_address);
1059 // #4. connect to remote server device.
1060 if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
1062 OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
1063 CALogSendStateInfo(svritem->sep.endpoint.adapter, svritem->sep.endpoint.addr,
1064 svritem->sep.endpoint.port, 0, false, strerror(errno));
1065 return CA_SOCKET_OPERATION_FAILED;
1068 OIC_LOG(INFO, TAG, "connect socket success");
1069 svritem->state = CONNECTED;
1070 ssize_t len = CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
1073 OIC_LOG(ERROR, TAG, "wakeup receive thread failed");
1074 return CA_SOCKET_OPERATION_FAILED;
1077 #if defined(__TIZEN__)
1078 // #5. Send HTTP CONNECT to proxy if proxy
1080 const char *cloud_address = CAGetCloudAddressForProxy();
1081 OIC_LOG_V(INFO, TAG, "Proxy : '%s'", cloud_address ? cloud_address : "(nil)");
1083 if(cloud_address && *cloud_address)
1086 int len = snprintf(message, 4096,
1087 "CONNECT %s HTTP/1.1\r\n"
1088 "Host: %s\r\n\r\n", cloud_address, cloud_address
1091 ssize_t l = send(fd, message, len, 0);
1094 OIC_LOG_V(ERROR, TAG, "failed to send HTTP CONNECT data (expected %d bytes, ret %zd)", len, l);
1097 return CA_SOCKET_OPERATION_FAILED;
1100 // maybe this should be called in other thread, it causes bottleneck.
1101 OIC_LOG_V(INFO, TAG, "Message sent is : '%s'\n", message);
1104 OIC_LOG_V(INFO, TAG, "Receiving response to CONNECT from proxy...");
1106 l = recv(fd, message, 4096, 0);
1108 OIC_LOG_V(INFO, TAG, "Received data : '%s'", message);
1109 OIC_LOG_V(INFO, TAG, "Received len = %zd", l);
1111 int status_code = CAGetHTTPStatusCode(message);
1113 OIC_LOG_V(INFO, TAG, "HTTP status_code : %d", status_code);
1114 if(status_code < 200 || status_code > 299)
1116 OIC_LOG_V(ERROR, TAG, "Error, Wrong status code: %d", status_code);
1119 return CA_SOCKET_OPERATION_FAILED;
1124 return CA_STATUS_OK;
1127 static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock)
1129 VERIFY_NON_NULL_RET(sock, TAG, "sock", -1);
1131 if (OC_INVALID_SOCKET != sock->fd)
1133 OIC_LOG(DEBUG, TAG, "accept socket created already");
1137 socklen_t socklen = 0;
1138 struct sockaddr_storage server = { .ss_family = family };
1140 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
1141 if (OC_INVALID_SOCKET == fd)
1143 OIC_LOG(ERROR, TAG, "Failed to create socket");
1147 if (family == AF_INET6)
1149 // the socket is restricted to sending and receiving IPv6 packets only.
1151 //TODO: enable once IPv6 is supported
1153 if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
1155 OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
1159 ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port);
1160 socklen = sizeof (struct sockaddr_in6);
1164 ((struct sockaddr_in *)&server)->sin_port = htons(sock->port);
1165 socklen = sizeof (struct sockaddr_in);
1169 if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
1171 OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
1175 if (-1 == bind(fd, (struct sockaddr *)&server, socklen))
1177 OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
1181 if (listen(fd, caglobals.tcp.listenBacklog) != 0)
1183 OIC_LOG(ERROR, TAG, "listen() error");
1187 if (sock->port) // use the given port
1190 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof (on)))
1192 OIC_LOG_V(ERROR, TAG, "SO_REUSEADDR failed: %s", strerror(errno));
1194 return OC_INVALID_SOCKET;
1197 else // return the assigned port
1199 if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen))
1201 OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
1204 sock->port = ntohs(family == AF_INET6 ?
1205 ((struct sockaddr_in6 *)&server)->sin6_port :
1206 ((struct sockaddr_in *)&server)->sin_port);
1216 return OC_INVALID_SOCKET;
1219 static void CAInitializePipe(int *fds)
1221 int ret = pipe(fds);
1222 // TODO: Remove temporary workaround once F_GETFD / F_SETFD support is in TizenRT
1223 /* Temporary workaround: By pass F_GETFD / F_SETFD */
1233 OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
1238 ret = fcntl(fds[0], F_GETFD);
1241 ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
1245 ret = fcntl(fds[1], F_GETFD);
1249 ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
1259 OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
1265 #ifndef DISABLE_TCP_SERVER
1266 #define NEWSOCKET(FAMILY, NAME) \
1267 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
1268 if (caglobals.tcp.NAME.fd == -1) \
1270 caglobals.tcp.NAME.port = 0; \
1271 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
1274 void CATCPInitializeSocket()
1276 #ifndef __WITH_TLS__
1277 NEWSOCKET(AF_INET, ipv4);
1279 NEWSOCKET(AF_INET, ipv4s);
1282 //TODO Enable once TizenRT supports IPv6
1284 #ifndef __WITH_TLS__
1285 NEWSOCKET(AF_INET6, ipv6);
1287 NEWSOCKET(AF_INET6, ipv6s);
1290 #ifndef __WITH_TLS__
1291 OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
1292 caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
1293 OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
1294 caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
1296 OIC_LOG_V(DEBUG, TAG, "IPv4 secure socket fd=%d, port=%d",
1297 caglobals.tcp.ipv4s.fd, caglobals.tcp.ipv4s.port);
1298 OIC_LOG_V(DEBUG, TAG, "IPv6 secure socket fd=%d, port=%d",
1299 caglobals.tcp.ipv6s.fd, caglobals.tcp.ipv6s.port);
1302 #endif // DISABLE_TCP_SERVER
1304 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
1306 oc_mutex_lock(g_mutexObjectList);
1307 if (caglobals.tcp.started)
1309 oc_mutex_unlock(g_mutexObjectList);
1310 OIC_LOG(INFO, TAG, "Adapter is started already");
1311 return CA_STATUS_OK;
1314 g_threadPool = threadPool;
1316 if (!caglobals.tcp.ipv4tcpenabled)
1318 caglobals.tcp.ipv4tcpenabled = true; // only needed to run CA tests
1320 if (!caglobals.tcp.ipv6tcpenabled)
1322 caglobals.tcp.ipv6tcpenabled = true; // only needed to run CA tests
1325 caglobals.tcp.terminate = false;
1326 if (!caglobals.tcp.svrlist)
1328 caglobals.tcp.svrlist = u_arraylist_create();
1331 #ifndef DISABLE_TCP_SERVER
1332 if (caglobals.server)
1334 CATCPInitializeSocket();
1339 // create pipe for fast shutdown
1340 CAInitializePipe(caglobals.tcp.shutdownFds);
1342 // create pipe for connection event
1343 CAInitializePipe(caglobals.tcp.connectionFds);
1345 CAResult_t res = CA_STATUS_OK;
1347 res = ca_thread_pool_add_task(g_threadPool, CAReceiveHandler, NULL, &g_taskId);
1349 res = ca_thread_pool_add_task(g_threadPool, CAReceiveHandler, NULL, NULL,
1350 "IoT_TCPReceive", CONFIG_IOTIVITY_TCPRECEIVE_PTHREAD_STACKSIZE);
1352 if (CA_STATUS_OK != res)
1354 oc_mutex_unlock(g_mutexObjectList);
1355 OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
1360 caglobals.tcp.started = true;
1361 oc_mutex_unlock(g_mutexObjectList);
1363 OIC_LOG(INFO, TAG, "CAReceiveHandler thread started successfully.");
1364 return CA_STATUS_OK;
1367 void CATCPStopServer()
1369 oc_mutex_lock(g_mutexObjectList);
1370 if (caglobals.tcp.terminate)
1372 oc_mutex_unlock(g_mutexObjectList);
1373 OIC_LOG(INFO, TAG, "Adapter is not enabled");
1377 // set terminate flag.
1378 caglobals.tcp.terminate = true;
1380 oc_mutex_lock(g_mutexSend);
1381 oc_cond_signal(g_condSend);
1382 oc_mutex_unlock(g_mutexSend);
1385 if (caglobals.tcp.started)
1387 oc_cond_wait(g_condObjectList, g_mutexObjectList);
1388 caglobals.tcp.started = false;
1392 // close accept socket.
1393 #ifndef __WITH_TLS__
1397 CLOSE_SOCKET(ipv4s);
1398 CLOSE_SOCKET(ipv6s);
1401 if (caglobals.tcp.connectionFds[1] != OC_INVALID_SOCKET)
1403 close(caglobals.tcp.connectionFds[1]);
1404 caglobals.tcp.connectionFds[1] = OC_INVALID_SOCKET;
1406 if (caglobals.tcp.connectionFds[0] != OC_INVALID_SOCKET)
1408 close(caglobals.tcp.connectionFds[0]);
1409 caglobals.tcp.connectionFds[0] = OC_INVALID_SOCKET;
1412 if (caglobals.tcp.shutdownFds[1] != OC_INVALID_SOCKET)
1414 close(caglobals.tcp.shutdownFds[1]);
1415 caglobals.tcp.shutdownFds[1] = OC_INVALID_SOCKET;
1416 // receive thread will stop immediately
1418 if (caglobals.tcp.started)
1420 oc_cond_wait(g_condObjectList, g_mutexObjectList);
1421 caglobals.tcp.started = false;
1423 if (caglobals.tcp.shutdownFds[0] != OC_INVALID_SOCKET)
1425 close(caglobals.tcp.shutdownFds[0]);
1426 caglobals.tcp.shutdownFds[0] = OC_INVALID_SOCKET;
1429 oc_mutex_unlock(g_mutexObjectList);
1432 ca_thread_pool_remove_task(g_threadPool, g_taskId);
1435 CATCPDisconnectAll();
1437 OIC_LOG(INFO, TAG, "Adapter terminated successfully");
1440 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
1442 g_packetReceivedCallback = callback;
1445 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
1447 g_connectionCallback = connHandler;
1450 size_t CACheckPayloadLengthFromHeader(const void *data, size_t dlen)
1452 VERIFY_NON_NULL_RET(data, TAG, "data", -1);
1454 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1455 ((unsigned char *)data)[0] >> 4);
1457 coap_pdu_t *pdu = coap_new_pdu2(transport, dlen);
1460 OIC_LOG(ERROR, TAG, "outpdu is null");
1461 OIC_LOG_V(ERROR, TAG, "data length: %zu", dlen);
1465 int ret = coap_pdu_parse2((unsigned char *) data, dlen, pdu, transport);
1468 OIC_LOG(ERROR, TAG, "pdu parse failed");
1469 coap_delete_pdu(pdu);
1473 size_t payloadLen = 0;
1474 size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
1475 OIC_LOG_V(DEBUG, TAG, "headerSize : %zu, pdu length : %d",
1476 headerSize, pdu->length);
1477 if (pdu->length > headerSize)
1479 payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
1487 static ssize_t sendData(const CAEndpoint_t *endpoint, const void *data,
1488 size_t dlen, const char *fam)
1490 OIC_LOG_V(INFO, TAG, "The length of data that needs to be sent is %zu bytes", dlen);
1492 // #1. find a session info from list.
1493 CASocketFd_t sockFd = CAGetSocketFDFromEndpoint(endpoint);
1494 if (OC_INVALID_SOCKET == sockFd)
1496 // if there is no connection info, connect to remote device.
1497 sockFd = CAConnectTCPSession(endpoint);
1498 if (OC_INVALID_SOCKET == sockFd)
1500 OIC_LOG(ERROR, TAG, "Failed to create tcp session object");
1505 // #2. send data to remote device.
1506 ssize_t remainLen = dlen;
1507 unsigned int sendRetryTime = 1;
1511 ssize_t len = send(sockFd, data, remainLen, MSG_DONTWAIT | MSG_NOSIGNAL);
1513 ssize_t len = send(sockFd, data, remainLen, MSG_DONTWAIT);
1517 g_lastErrorCode = errno;
1518 OIC_LOG_V(DEBUG, TAG, "Set g_lastErrorCode to %s", strerror(g_lastErrorCode));
1519 if (EWOULDBLOCK != g_lastErrorCode && EAGAIN != g_lastErrorCode)
1521 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(g_lastErrorCode));
1522 CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
1523 len, false, strerror(g_lastErrorCode));
1527 // re-trying send after 10, 20, 40, 80, 160 and 320 milliseconds
1528 if (sendRetryTime > 32)
1533 unsigned int waitTime = sendRetryTime * 10 * MILLISECONDS_PER_SECOND;
1534 OIC_LOG_V(WARNING, TAG, "send blocked. trying send after %u microseconds", waitTime);
1536 oc_mutex_lock(g_mutexSend);
1537 oc_cond_wait_for(g_condSend, g_mutexSend, waitTime);
1538 oc_mutex_unlock(g_mutexSend);
1540 oc_mutex_lock(g_mutexObjectList);
1541 if (caglobals.tcp.terminate)
1543 oc_mutex_unlock(g_mutexObjectList);
1546 oc_mutex_unlock(g_mutexObjectList);
1548 sendRetryTime = (sendRetryTime << 1);
1555 } while (remainLen > 0);
1560 OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
1561 CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
1566 ssize_t CATCPSendData(CAEndpoint_t *endpoint, const void *data, size_t datalen)
1568 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", -1);
1569 VERIFY_NON_NULL_RET(data, TAG, "data is NULL", -1);
1571 if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
1573 return sendData(endpoint, data, datalen, "ipv6");
1575 if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
1577 return sendData(endpoint, data, datalen, "ipv4");
1580 OIC_LOG(ERROR, TAG, "Not supported transport flags");
1584 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1586 VERIFY_NON_NULL(info, TAG, "info is NULL");
1587 VERIFY_NON_NULL(size, TAG, "size is NULL");
1589 return CA_NOT_SUPPORTED;
1592 CASocketFd_t CAConnectTCPSession(const CAEndpoint_t *endpoint)
1594 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1596 // #1. create TCP server object
1597 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
1600 OIC_LOG(ERROR, TAG, "Out of memory");
1601 return OC_INVALID_SOCKET;
1603 memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
1604 svritem->sep.endpoint.adapter = endpoint->adapter;
1605 svritem->sep.endpoint.port = endpoint->port;
1606 svritem->sep.endpoint.flags = endpoint->flags;
1607 svritem->sep.endpoint.ifindex = endpoint->ifindex;
1608 svritem->state = CONNECTING;
1609 svritem->isClient = true;
1611 // Allocate message buffer
1612 svritem->tlsdata = (unsigned char*) OICCalloc(TLS_DATA_MAX_SIZE, sizeof(unsigned char));
1613 if (!svritem->tlsdata)
1615 OIC_LOG(ERROR, TAG, "Out of memory");
1617 return OC_INVALID_SOCKET;
1620 // #2. add TCP connection info to list
1621 oc_mutex_lock(g_mutexObjectList);
1622 if (caglobals.tcp.svrlist)
1624 bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
1627 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
1629 OICFree(svritem->tlsdata);
1631 oc_mutex_unlock(g_mutexObjectList);
1632 return OC_INVALID_SOCKET;
1635 oc_mutex_unlock(g_mutexObjectList);
1637 // #3. create the socket and connect to TCP server
1638 int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
1639 if (CA_STATUS_OK != CATCPCreateSocket(family, svritem))
1641 return OC_INVALID_SOCKET;
1644 // #4. pass the connection information to CA Common Layer.
1645 if (g_connectionCallback)
1647 g_connectionCallback(&(svritem->sep.endpoint), true, svritem->isClient);
1653 CAResult_t CADisconnectTCPSession(size_t index)
1655 CATCPSessionInfo_t *removedData = u_arraylist_remove(caglobals.tcp.svrlist, index);
1658 OIC_LOG(DEBUG, TAG, "there is no data to be removed");
1659 return CA_STATUS_OK;
1662 // close the socket and remove session info in list.
1663 if (removedData->fd >= 0)
1665 shutdown(removedData->fd, SHUT_RDWR);
1666 close(removedData->fd);
1667 removedData->fd = -1;
1668 removedData->state = (CONNECTED == removedData->state) ?
1669 DISCONNECTED : removedData->state;
1671 // pass the connection information to CA Common Layer.
1672 if (g_connectionCallback && DISCONNECTED == removedData->state)
1674 g_connectionCallback(&(removedData->sep.endpoint), false, removedData->isClient);
1677 OICFree(removedData->data);
1678 removedData->data = NULL;
1680 OICFree(removedData->tlsdata);
1681 removedData->tlsdata = NULL;
1683 OICFree(removedData);
1686 OIC_LOG(DEBUG, TAG, "data is removed from session list");
1688 #ifndef DISABLE_TCP_SERVER
1689 if (caglobals.server && MAX_CONNECTION_COUNTS == u_arraylist_length(caglobals.tcp.svrlist) + 1)
1691 CATCPInitializeSocket();
1695 return CA_STATUS_OK;
1698 void CATCPDisconnectAll()
1700 OIC_LOG(DEBUG, TAG, "IN - CATCPDisconnectAll");
1702 oc_mutex_lock(g_mutexObjectList);
1704 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1705 for (ssize_t index = length; index > 0; index--)
1707 // disconnect session from remote device.
1708 CADisconnectTCPSession(index - 1);
1711 u_arraylist_destroy(caglobals.tcp.svrlist);
1712 caglobals.tcp.svrlist = NULL;
1714 oc_mutex_unlock(g_mutexObjectList);
1717 CAcloseSslConnectionAll(CA_ADAPTER_TCP);
1720 OIC_LOG(DEBUG, TAG, "OUT - CATCPDisconnectAll");
1723 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
1725 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1726 VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
1728 OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1730 // get connection info from list
1731 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1732 for (size_t i = 0; i < length; i++)
1734 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1735 caglobals.tcp.svrlist, i);
1741 if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1742 sizeof(svritem->sep.endpoint.addr))
1743 && (svritem->sep.endpoint.port == endpoint->port)
1744 && (svritem->sep.endpoint.flags & endpoint->flags))
1746 OIC_LOG(DEBUG, TAG, "Found in session list");
1752 OIC_LOG(DEBUG, TAG, "Session not found");
1756 CASocketFd_t CAGetSocketFDFromEndpoint(const CAEndpoint_t *endpoint)
1758 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1760 OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1762 // get connection info from list.
1763 oc_mutex_lock(g_mutexObjectList);
1764 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1765 for (size_t i = 0; i < length; i++)
1767 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1768 caglobals.tcp.svrlist, i);
1774 if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1775 sizeof(svritem->sep.endpoint.addr))
1776 && (svritem->sep.endpoint.port == endpoint->port)
1777 && (svritem->sep.endpoint.flags & endpoint->flags))
1779 oc_mutex_unlock(g_mutexObjectList);
1780 OIC_LOG(DEBUG, TAG, "Found in session list");
1785 oc_mutex_unlock(g_mutexObjectList);
1786 OIC_LOG(DEBUG, TAG, "Session not found");
1787 return OC_INVALID_SOCKET;
1790 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1793 // check from the last item.
1794 CATCPSessionInfo_t *svritem = NULL;
1795 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1796 for (size_t i = 0; i < length; i++)
1798 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1800 if (svritem && svritem->fd == fd)
1803 oc_mutex_unlock(g_mutexObjectList);
1812 static CATCPSessionInfo_t *CAGetSessionInfoFromFDAsOwner(int fd, size_t *index)
1814 CATCPSessionInfo_t *svritem = NULL;
1815 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1816 for (size_t i = 0; i < length; i++)
1818 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1820 if (svritem && svritem->fd == fd)
1830 CAResult_t CASearchAndDeleteTCPSession(const CAEndpoint_t *endpoint)
1832 oc_mutex_lock(g_mutexObjectList);
1834 CAResult_t result = CA_STATUS_OK;
1836 CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1839 result = CADisconnectTCPSession(index);
1840 if (CA_STATUS_OK != result)
1842 OIC_LOG_V(ERROR, TAG, "CADisconnectTCPSession failed, result[%d]", result);
1846 oc_mutex_unlock(g_mutexObjectList);
1850 void CATCPCloseInProgressConnections()
1852 OIC_LOG(INFO, TAG, "IN - CATCPCloseInProgressConnections");
1854 oc_mutex_lock(g_mutexObjectList);
1856 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1857 for (size_t index = 0; index < length; index++)
1859 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1860 caglobals.tcp.svrlist, index);
1866 // Session which are connecting state
1867 if (svritem->fd >= 0 && svritem->state == CONNECTING)
1869 shutdown(svritem->fd, SHUT_RDWR);
1872 svritem->state = DISCONNECTED;
1876 oc_mutex_unlock(g_mutexObjectList);
1878 OIC_LOG(INFO, TAG, "OUT - CATCPCloseInProgressConnections");
1881 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1883 OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1885 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1886 ((unsigned char *)recvBuffer)[0] >> 4);
1887 size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1889 size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1891 OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%zu]", optPaylaodLen);
1892 OIC_LOG_V(DEBUG, TAG, "header length [%zu]", headerLen);
1893 OIC_LOG_V(DEBUG, TAG, "total data length [%zu]", headerLen + optPaylaodLen);
1895 OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1896 return headerLen + optPaylaodLen;
1899 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1901 g_tcpErrorHandler = errorHandleCallback;
1904 CAResult_t CASetKeepAlive(const CAEndpoint_t *endpoint, int time, int cnt, int intvl)
1906 OIC_LOG(INFO, TAG, "IN - CATCPSetKeepAlive");
1908 VERIFY_NON_NULL(endpoint, TAG, "endpoint is NULL");
1911 bool revertKeepAliveSetting = false;
1912 CAResult_t result = CA_STATUS_OK;
1913 oc_mutex_lock(g_mutexObjectList);
1914 CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1917 // There is no connection with the given endpoint, so the parameter is considered to be invalid.
1918 result = CA_STATUS_INVALID_PARAM;
1922 if (svritem->fd < 0 || svritem->state != CONNECTED)
1924 result = CA_DESTINATION_DISCONNECTED;
1929 if (-1 == setsockopt(svritem->fd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option)))
1931 OIC_LOG_V(ERROR, TAG, "setsockopt SO_KEEPALIVE failed on socket(%d): %s",
1932 svritem->fd, strerror(errno));
1933 result = CA_SOCKET_OPERATION_FAILED;
1937 if (-1 == setsockopt(svritem->fd, SOL_TCP, TCP_KEEPIDLE, &time, sizeof(time)))
1939 OIC_LOG_V(ERROR, TAG, "setsockopt TCP_KEEPIDLE failed on socket(%d): %s",
1940 svritem->fd, strerror(errno));
1941 revertKeepAliveSetting = true;
1942 result = CA_SOCKET_OPERATION_FAILED;
1946 if (-1 == setsockopt(svritem->fd, SOL_TCP, TCP_KEEPCNT, &cnt, sizeof(cnt)))
1948 OIC_LOG_V(ERROR, TAG, "setsockopt TCP_KEEPCNT failed on socket(%d): %s",
1949 svritem->fd, strerror(errno));
1950 revertKeepAliveSetting = true;
1951 result = CA_SOCKET_OPERATION_FAILED;
1955 if (-1 == setsockopt(svritem->fd, SOL_TCP, TCP_KEEPINTVL, &intvl, sizeof(intvl)))
1957 OIC_LOG_V(ERROR, TAG, "setsockopt TCP_KEEPINTVL failed on socket(%d): %s",
1958 svritem->fd, strerror(errno));
1959 revertKeepAliveSetting = true;
1960 result = CA_SOCKET_OPERATION_FAILED;
1964 if (revertKeepAliveSetting)
1966 // Unset SO_KEEPALIVE
1968 if (-1 == setsockopt(svritem->fd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option)))
1970 OIC_LOG_V(ERROR, TAG, "unset SO_KEEPALIVE failed on socket(%d): %s",
1971 svritem->fd, strerror(errno));
1974 oc_mutex_unlock(g_mutexObjectList);
1975 OIC_LOG(INFO, TAG, "OUT - CATCPSetKeepAlive");
1979 CAResult_t CAUnSetKeepAlive(const CAEndpoint_t *endpoint)
1981 OIC_LOG(INFO, TAG, "IN - CATCPUnSetKeepAlive");
1983 VERIFY_NON_NULL(endpoint, TAG, "endpoint is NULL");
1986 CAResult_t result = CA_STATUS_OK;
1987 oc_mutex_lock(g_mutexObjectList);
1988 CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1991 // There is no connection with the given endpoint, so the parameter is considered to be invalid.
1992 result = CA_STATUS_INVALID_PARAM;
1996 if (svritem->fd < 0 || svritem->state != CONNECTED)
1998 result = CA_DESTINATION_DISCONNECTED;
2003 if (-1 == setsockopt(svritem->fd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option)))
2005 OIC_LOG_V(ERROR, TAG, "setsockopt SO_KEEPALIVE failed on socket(%d): %s",
2006 svritem->fd, strerror(errno));
2007 result = CA_SOCKET_OPERATION_FAILED;
2011 oc_mutex_unlock(g_mutexObjectList);
2012 OIC_LOG(INFO, TAG, "OUT - CATCPUnSetKeepAlive");
2016 int CAGetLastErrorCode()
2018 return g_lastErrorCode;