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>
25 #include <tinyara/config.h>
33 #include <arpa/inet.h>
34 #include <netinet/in.h>
39 #include <sys/socket.h>
40 #include <netinet/in.h>
44 #include "catcpinterface.h"
45 #include "caipnwmonitor.h"
47 #include "caadapterutils.h"
49 #include "oic_malloc.h"
50 #include "oic_string.h"
53 #include "ca_adapter_net_ssl.h"
57 * Logging tag for module name.
59 //#define TAG "OIC_CA_TCP_SERVER"
60 #define TAG TCP_SERVER_TAG
63 * Maximum CoAP over TCP header length
64 * to know the total data length.
66 #define COAP_MAX_HEADER_SIZE 6
71 #define TLS_HEADER_SIZE 5
74 * Max Connection Counts.
76 #define MAX_CONNECTION_COUNTS 500
78 #define COAP_TCP_MAX_BUFFER_CHUNK_SIZE 65530 //64kb - 6 (coap+tcp max header size)
80 #define MILLISECONDS_PER_SECOND (1000)
85 static ca_thread_pool_t g_threadPool = NULL;
90 static uint32_t g_taskId = 0;
93 * Mutex to synchronize device object list.
95 static oc_mutex g_mutexObjectList = NULL;
98 * Conditional mutex to synchronize.
100 static oc_cond g_condObjectList = NULL;
103 * Mutex to synchronize send.
105 static oc_mutex g_mutexSend = NULL;
108 * Conditional mutex to synchronize send.
110 static oc_cond g_condSend = NULL;
113 * Maintains the callback to be notified when data received from remote device.
115 static CATCPPacketReceivedCallback g_packetReceivedCallback = NULL;
118 * Error callback to update error in TCP.
120 static CATCPErrorHandleCallback g_tcpErrorHandler = NULL;
123 * Connected Callback to pass the connection information to RI.
125 static CATCPConnectionHandleCallback g_connectionCallback = NULL;
127 static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock);
128 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock);
129 static void CAFindReadyMessage();
130 static void CAPollReturned(struct pollfd *readFds, size_t size);
131 static void CAReceiveMessage(int fd);
132 static void CAReceiveHandler(void *data);
133 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem);
134 static void CATCPInitializeSocket();
135 static CATCPSessionInfo_t *CAGetSessionInfoFromFDAsOwner(int fd, size_t *index);
137 #if defined(__TIZEN__)
138 static char g_cloudproxyUri[CA_MAX_URI_LENGTH];
140 CAResult_t CASetCloudAddressForProxy(const char *uri)
143 memset(g_cloudproxyUri, '\0', sizeof (g_cloudproxyUri));
145 OICStrcpy(g_cloudproxyUri, sizeof (g_cloudproxyUri), uri);
149 const char *CAGetCloudAddressForProxy()
151 if (g_cloudproxyUri[0] == '\0')
153 return g_cloudproxyUri;
157 #define MAX_TCP_SOCK_COUNT 4
159 #define CLOSE_SOCKET(TYPE) \
160 if (caglobals.tcp.TYPE.fd != OC_INVALID_SOCKET) \
162 close(caglobals.tcp.TYPE.fd); \
163 caglobals.tcp.TYPE.fd = OC_INVALID_SOCKET; \
166 #define CA_FD_SET(TYPE, FDS, COUNT) \
167 FDS[COUNT].fd = caglobals.tcp.TYPE.fd; \
168 FDS[COUNT].events = POLLIN;
170 void CATCPDestroyMutex()
172 if (g_mutexObjectList)
174 oc_mutex_free(g_mutexObjectList);
175 g_mutexObjectList = NULL;
179 CAResult_t CATCPCreateMutex()
181 if (!g_mutexObjectList)
183 g_mutexObjectList = oc_mutex_new();
184 if (!g_mutexObjectList)
186 OIC_LOG(ERROR, TAG, "Failed to create mutex!");
187 return CA_STATUS_FAILED;
194 void CATCPDestroyCond()
196 if (g_condObjectList)
198 oc_cond_free(g_condObjectList);
199 g_condObjectList = NULL;
203 CAResult_t CATCPCreateCond()
205 if (!g_condObjectList)
207 g_condObjectList = oc_cond_new();
208 if (!g_condObjectList)
210 OIC_LOG(ERROR, TAG, "Failed to create cond!");
211 return CA_STATUS_FAILED;
217 void CATCPDestroySendMutex()
221 oc_mutex_free(g_mutexSend);
226 CAResult_t CATCPCreateSendMutex()
230 g_mutexSend = oc_mutex_new();
233 OIC_LOG(ERROR, TAG, "Failed to create send mutex!");
234 return CA_STATUS_FAILED;
241 void CATCPDestroySendCond()
245 oc_cond_free(g_condSend);
250 CAResult_t CATCPCreateSendCond()
254 g_condSend = oc_cond_new();
257 OIC_LOG(ERROR, TAG, "Failed to create send cond!");
258 return CA_STATUS_FAILED;
264 static void CAReceiveHandler(void *data)
267 OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler");
271 oc_mutex_lock(g_mutexObjectList);
272 if (caglobals.tcp.terminate)
274 oc_mutex_unlock(g_mutexObjectList);
277 oc_mutex_unlock(g_mutexObjectList);
278 CAFindReadyMessage();
281 oc_mutex_lock(g_mutexObjectList);
282 oc_cond_signal(g_condObjectList);
283 oc_mutex_unlock(g_mutexObjectList);
285 OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
288 static void CAFindReadyMessage()
290 int timeout = (caglobals.tcp.selectTimeout * 1000);
293 oc_mutex_lock(g_mutexObjectList);
294 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
296 // Consider 4 tcp sockets(ipv4, ipv4s, ipv6, ipv6s) + 1 connection fd + all sockets in svrlist
297 struct pollfd *readFds = (struct pollfd *)OICCalloc(MAX_TCP_SOCK_COUNT + 1 + length, sizeof(struct pollfd));
300 OIC_LOG_V(ERROR, TAG, "Failed to allocate memory!");
301 oc_mutex_unlock(g_mutexObjectList);
306 CA_FD_SET(ipv4, readFds, counter);
308 CA_FD_SET(ipv4s, readFds, counter);
310 CA_FD_SET(ipv6, readFds, counter);
312 CA_FD_SET(ipv6s, readFds, counter);
316 readFds[counter].fd = caglobals.tcp.connectionFds[0];
317 readFds[counter].events = POLLIN;
320 // All sockets in svrlist
321 for (size_t i = 0; i < length; i++)
323 CATCPSessionInfo_t *svritem =
324 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
325 if (svritem && 0 <= svritem->fd && CONNECTED == svritem->state)
327 readFds[counter].fd = svritem->fd;
328 readFds[counter].events = POLLIN;
332 oc_mutex_unlock(g_mutexObjectList);
333 int ret = poll(readFds, counter, timeout);
335 oc_mutex_lock(g_mutexObjectList);
336 if (caglobals.tcp.terminate)
338 OIC_LOG_V(INFO, TAG, "Packet receiver Stop request received.");
339 oc_mutex_unlock(g_mutexObjectList);
343 oc_mutex_unlock(g_mutexObjectList);
347 CAPollReturned(readFds, counter);
351 usleep(1000); /* some of the fields are not set by kernel on repeatedly calling
352 poll.Applying a timeout will solve this*/
356 OIC_LOG_V(FATAL, TAG, "poll error %s", strerror(errno));
362 static void CAPollReturned(struct pollfd *readFds, size_t size)
364 VERIFY_NON_NULL_VOID(readFds, TAG, "readFds is NULL");
366 if (caglobals.tcp.ipv4.fd != -1 && readFds[0].revents == POLLIN)
368 CAAcceptConnection(CA_IPV4, &caglobals.tcp.ipv4);
371 else if (caglobals.tcp.ipv4s.fd != -1 && readFds[1].revents == POLLIN)
373 CAAcceptConnection(CA_IPV4 | CA_SECURE, &caglobals.tcp.ipv4s);
376 else if (caglobals.tcp.ipv6.fd != -1 && readFds[2].revents == POLLIN)
378 CAAcceptConnection(CA_IPV6, &caglobals.tcp.ipv6);
381 else if (caglobals.tcp.ipv6s.fd != -1 && readFds[3].revents == POLLIN)
383 CAAcceptConnection(CA_IPV6 | CA_SECURE, &caglobals.tcp.ipv6s);
386 else if (-1 != caglobals.tcp.connectionFds[0] && readFds[4].revents != 0)
388 // new connection was created from remote device.
389 // exit the function to update read file descriptor.
390 char buf[MAX_ADDR_STR_SIZE_CA] = {0};
391 ssize_t len = read(caglobals.tcp.connectionFds[0], buf, sizeof (buf));
396 OIC_LOG_V(DEBUG, TAG, "Received new connection event with [%s]", buf);
401 int *readFDList = NULL;
402 size_t readFDListSize = 0;
404 oc_mutex_lock(g_mutexObjectList);
405 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
407 readFDList = (int*) OICCalloc(length, sizeof(int));
408 if (NULL == readFDList)
410 OIC_LOG_V(ERROR, TAG, "Failed to allocate memory!");
411 oc_mutex_unlock(g_mutexObjectList);
415 for (size_t i = 0; i < length; i++)
417 CATCPSessionInfo_t *svritem =
418 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
419 if (svritem && svritem->fd >= 0)
424 if (svritem->fd == readFds[j].fd)
431 if (j < size && readFds[j].revents != 0)
433 readFDList[readFDListSize++] = svritem->fd;
437 oc_mutex_unlock(g_mutexObjectList);
439 // Read incomming messages from fds
440 for (size_t i = 0; i < readFDListSize; i++)
442 CAReceiveMessage(readFDList[i]);
449 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock)
451 OIC_LOG_V(INFO, TAG, "In %s", __func__);
452 VERIFY_NON_NULL_VOID(sock, TAG, "sock is NULL");
454 if (MAX_CONNECTION_COUNTS == u_arraylist_length(caglobals.tcp.svrlist))
456 OIC_LOG_V(INFO, TAG, "Exceeding the max connection counts limit, close listening port");
458 sock->fd = OC_INVALID_SOCKET;
462 struct sockaddr_storage clientaddr;
463 socklen_t clientlen = sizeof (struct sockaddr_in);
466 clientlen = sizeof(struct sockaddr_in6);
469 CASocketFd_t sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen);
470 if (OC_INVALID_SOCKET != sockfd)
472 CATCPSessionInfo_t *svritem =
473 (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
476 OIC_LOG(ERROR, TAG, "Out of memory");
481 svritem->fd = sockfd;
482 svritem->sep.endpoint.flags = flag;
483 svritem->sep.endpoint.adapter = CA_ADAPTER_TCP;
484 svritem->state = CONNECTED;
485 svritem->isClient = false;
486 CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
487 svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
489 // Allocate message buffer
490 svritem->tlsdata = (unsigned char*) OICCalloc(TLS_DATA_MAX_SIZE, sizeof(unsigned char));
491 if (!svritem->tlsdata)
493 OIC_LOG(ERROR, TAG, "Out of memory");
499 oc_mutex_lock(g_mutexObjectList);
500 bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem);
503 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
505 OICFree(svritem->tlsdata);
507 oc_mutex_unlock(g_mutexObjectList);
510 oc_mutex_unlock(g_mutexObjectList);
512 // pass the connection information to CA Common Layer.
513 if (g_connectionCallback)
515 g_connectionCallback(&(svritem->sep.endpoint), true, svritem->isClient);
518 OIC_LOG_V(INFO, TAG, "Out %s", __func__);
522 * Clean socket state data
524 * @param[in/out] item - socket state data
526 void CACleanData(CATCPSessionInfo_t *svritem)
530 OICFree(svritem->data);
531 svritem->data = NULL;
536 svritem->totalLen = 0;
538 svritem->protocol = UNKNOWN;
543 * Construct CoAP header and payload from buffer
545 * @param[in] svritem - used socket, buffer, current received message length and protocol
546 * @param[in/out] data - data buffer, this value is updated as data is copied to svritem
547 * @param[in/out] dataLength - length of data, this value decreased as data is copied to svritem
548 * @return - CA_STATUS_OK or appropriate error code
550 CAResult_t CAConstructCoAP(CATCPSessionInfo_t *svritem, unsigned char **data,
553 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
555 if (NULL == svritem || NULL == data || NULL == dataLength)
557 OIC_LOG(ERROR, TAG, "Invalid input parameter(NULL)");
558 return CA_STATUS_INVALID_PARAM;
561 unsigned char *inBuffer = *data;
562 size_t inLen = *dataLength;
563 OIC_LOG_V(DEBUG, TAG, "before-datalength : %zd", *dataLength);
565 if (NULL == svritem->data && inLen > 0)
567 // allocate memory for message header (CoAP header size because it is bigger)
568 svritem->data = (unsigned char *) OICCalloc(1, COAP_MAX_HEADER_SIZE);
569 if (NULL == svritem->data)
571 OIC_LOG(ERROR, TAG, "OICCalloc - out of memory");
572 return CA_MEMORY_ALLOC_FAILED;
575 // copy 1 byte to parse coap header length
576 memcpy(svritem->data, inBuffer, 1);
578 svritem->bufLen = COAP_MAX_HEADER_SIZE;
583 //if not enough data received - read them on next CAFillHeader() call
589 //if enough data received - parse header
590 svritem->protocol = COAP;
592 //seems CoAP data received. read full coap header.
593 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(svritem->data[0] >> 4);
594 size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
598 if (svritem->len < headerLen)
600 copyLen = headerLen - svritem->len;
606 //read required bytes to have full CoAP header
607 memcpy(svritem->data + svritem->len, inBuffer, copyLen);
608 svritem->len += copyLen;
612 //if not enough data received - read them on next CAFillHeader() call
613 if (svritem->len < headerLen)
617 OIC_LOG(DEBUG, TAG, "CoAP header received partially. Wait for rest header data");
621 //calculate CoAP message length
622 svritem->totalLen = CAGetTotalLengthFromHeader(svritem->data);
628 // Calculate length of data to be copied.
629 copyLen = svritem->totalLen - svritem->len;
635 // Is buffer not big enough for remaining data ?
636 if (svritem->len + copyLen > svritem->bufLen)
638 // Resize buffer to accommodate enough space
639 size_t extLen = svritem->totalLen - svritem->bufLen;
640 if (extLen > COAP_TCP_MAX_BUFFER_CHUNK_SIZE)
642 extLen = COAP_TCP_MAX_BUFFER_CHUNK_SIZE;
645 // Allocate required memory
646 unsigned char *buffer = OICRealloc(svritem->data, svritem->bufLen + extLen);
649 OIC_LOG(ERROR, TAG, "OICRealloc - out of memory");
650 return CA_MEMORY_ALLOC_FAILED;
653 svritem->data = buffer;
654 svritem->bufLen += extLen;
657 // Read required bytes to have full CoAP payload
658 memcpy(svritem->data + svritem->len, inBuffer, copyLen);
659 svritem->len += copyLen;
667 OIC_LOG_V(DEBUG, TAG, "after-datalength : %zd", *dataLength);
668 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
672 static void CAReceiveMessage(int fd)
674 CAResult_t res = CA_STATUS_OK;
676 oc_mutex_lock(g_mutexObjectList);
678 //get remote device information from file descriptor.
680 CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFDAsOwner(fd, &index);
683 OIC_LOG(ERROR, TAG, "there is no connection information in list");
684 oc_mutex_unlock(g_mutexObjectList);
688 CASecureEndpoint_t peerEP = svritem->sep;
690 if (svritem->sep.endpoint.flags & CA_SECURE) // Secure connection
692 svritem->protocol = TLS;
696 size_t tlsLength = 0;
698 if (TLS_HEADER_SIZE > svritem->tlsLen)
700 nbRead = TLS_HEADER_SIZE - svritem->tlsLen;
704 //[3][4] bytes in tls header are tls payload length
705 tlsLength = TLS_HEADER_SIZE +
706 (size_t)((svritem->tlsdata[3] << 8) | svritem->tlsdata[4]);
707 OIC_LOG_V(DEBUG, TAG, "total tls length = %zd", tlsLength);
708 if (tlsLength > TLS_DATA_MAX_SIZE)
710 OIC_LOG_V(ERROR, TAG, "total tls length is too big (buffer size : %u)",
712 oc_mutex_unlock(g_mutexObjectList);
713 CATCPDisconnectSession(&peerEP.endpoint);
716 nbRead = tlsLength - svritem->tlsLen;
719 len = recv(fd, svritem->tlsdata + svritem->tlsLen, nbRead, 0);
722 OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno));
723 res = CA_RECEIVE_FAILED;
727 OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
728 svritem->state = DISCONNECTED;
729 res = CA_DESTINATION_DISCONNECTED;
733 svritem->tlsLen += len;
734 OIC_LOG_V(DEBUG, TAG, "nb_read : %zd bytes , recv() : %d bytes, svritem->tlsLen : %zd bytes",
735 nbRead, len, svritem->tlsLen);
736 if (tlsLength > 0 && tlsLength == svritem->tlsLen)
738 // When successfully read data - pass them to callback.
739 // Dont invoke callback locking mutex
740 unsigned char *mesBuf = svritem->tlsdata;
741 size_t mesBufLen = svritem->tlsLen;
742 svritem->tlsdata = NULL;
743 oc_mutex_unlock(g_mutexObjectList);
745 res = CAdecryptSsl(&peerEP, (uint8_t *)mesBuf, mesBufLen);
746 OIC_LOG_V(INFO, TAG, "%s: CAdecryptSsl returned %d", __func__, res);
748 // Check for the svritem and reset buffer
749 oc_mutex_lock(g_mutexObjectList);
750 svritem = CAGetSessionInfoFromFDAsOwner(fd, &index);
753 svritem->tlsdata = mesBuf;
758 // svritem does not exist, thus free the message buffer
759 OIC_LOG(ERROR, TAG, "svritem not found. Freeing message buffer!");
766 else // Non-Secure connection
768 svritem->protocol = COAP;
770 // svritem->tlsdata can also be used as receiving buffer in case of raw tcp
771 len = recv(fd, svritem->tlsdata, TLS_DATA_MAX_SIZE, 0);
774 OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno));
775 res = CA_RECEIVE_FAILED;
779 OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
780 res = CA_DESTINATION_DISCONNECTED;
784 //when successfully read data - pass them to callback.
785 OIC_LOG_V(DEBUG, TAG, "recv() : %d bytes", len);
786 if (g_packetReceivedCallback)
788 // Dont invoke callback locking mutex
789 unsigned char *mesBuf = svritem->tlsdata;
790 svritem->tlsdata = NULL;
791 oc_mutex_unlock(g_mutexObjectList);
793 res = g_packetReceivedCallback(&peerEP, mesBuf, len);
795 // Check for the svritem and reset buffer
796 oc_mutex_lock(g_mutexObjectList);
797 svritem = CAGetSessionInfoFromFDAsOwner(fd, &index);
800 svritem->tlsdata = mesBuf;
805 // svritem does not exist, thus free the message buffer
806 OIC_LOG(ERROR, TAG, "svritem not found. Freeing message buffer!");
813 oc_mutex_unlock(g_mutexObjectList);
815 if (res != CA_STATUS_OK)
817 CATCPDisconnectSession(&peerEP.endpoint);
821 static ssize_t CAWakeUpForReadFdsUpdate(const char *host)
823 if (caglobals.tcp.connectionFds[1] != -1)
828 len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
829 } while ((len == -1) && (errno == EINTR));
831 if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
833 OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
840 static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port,
841 struct sockaddr_storage *sockaddr)
843 struct addrinfo *addrs = NULL;
844 struct addrinfo hints = { .ai_family = family,
845 .ai_protocol = IPPROTO_TCP,
846 .ai_socktype = SOCK_STREAM,
847 .ai_flags = AI_NUMERICHOST };
849 int r = getaddrinfo(host, NULL, &hints, &addrs);
854 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: errno %s", strerror(errno));
858 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: %s", gai_strerror(r));
861 return CA_STATUS_FAILED;
863 // assumption: in this case, getaddrinfo will only return one addrinfo
864 // or first is the one we want.
865 if (addrs[0].ai_family == AF_INET6)
867 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6));
868 ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port);
872 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in));
873 ((struct sockaddr_in *)sockaddr)->sin_port = htons(port);
879 #if defined(__TIZEN__)
880 static int CAGetHTTPStatusCode(char * response) {
881 char *resp, *code_plus, *ptrSave;
884 resp = strdup(response);
885 strtok_r(resp, " ", &ptrSave); /* skip HTTP version */
886 code_plus = strtok_r(NULL, " ", &ptrSave);
888 ret = code_plus ? atoi(code_plus) : -1;
894 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
896 VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
898 OIC_LOG_V(INFO, TAG, "try to connect with [%s:%u]",
899 svritem->sep.endpoint.addr, svritem->sep.endpoint.port);
901 // #1. create tcp socket.
902 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
905 OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
906 return CA_SOCKET_OPERATION_FAILED;
910 // #2. convert address from string to binary.
911 struct sockaddr_storage sa = { .ss_family = family };
912 CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr,
913 svritem->sep.endpoint.port, &sa);
914 if (CA_STATUS_OK != res)
916 OIC_LOG(ERROR, TAG, "convert name to sockaddr failed");
917 return CA_SOCKET_OPERATION_FAILED;
920 // #3. set socket length.
921 socklen_t socklen = 0;
922 if (sa.ss_family == AF_INET6)
924 struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
925 if (!sock6->sin6_scope_id)
927 sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
929 socklen = sizeof(struct sockaddr_in6);
933 socklen = sizeof(struct sockaddr_in);
936 // #4. connect to remote server device.
937 if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
939 OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
940 CALogSendStateInfo(svritem->sep.endpoint.adapter, svritem->sep.endpoint.addr,
941 svritem->sep.endpoint.port, 0, false, strerror(errno));
942 return CA_SOCKET_OPERATION_FAILED;
945 OIC_LOG(INFO, TAG, "connect socket success");
946 svritem->state = CONNECTED;
947 ssize_t len = CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
950 OIC_LOG(ERROR, TAG, "wakeup receive thread failed");
951 return CA_SOCKET_OPERATION_FAILED;
954 #if defined(__TIZEN__)
955 // #5. Send HTTP CONNECT to proxy if proxy
957 const char *cloud_address = CAGetCloudAddressForProxy();
958 OIC_LOG_V(INFO, TAG, "Proxy : '%s'", cloud_address ? cloud_address : "(nil)");
960 if(cloud_address && *cloud_address)
963 int len = sprintf(message,
964 "CONNECT %s HTTP/1.1\r\n"
965 "Host: %s\r\n\r\n", cloud_address, cloud_address
968 ssize_t l = send(fd, message, len, 0);
971 OIC_LOG_V(ERROR, TAG, "failed to send HTTP CONNECT data (expected %d bytes, ret %zd)", len, l);
974 return CA_SOCKET_OPERATION_FAILED;
977 // maybe this should be called in other thread, it causes bottleneck.
978 OIC_LOG_V(INFO, TAG, "Message sent is : '%s'\n", message);
981 OIC_LOG_V(INFO, TAG, "Receiving response to CONNECT from proxy...");
983 l = recv(fd, message, 4096, 0);
985 OIC_LOG_V(INFO, TAG, "Received data : '%s'", message);
986 OIC_LOG_V(INFO, TAG, "Received len = %zd", l);
988 int status_code = CAGetHTTPStatusCode(message);
990 OIC_LOG_V(INFO, TAG, "HTTP status_code : %d", status_code);
991 if(status_code < 200 || status_code > 299)
993 OIC_LOG_V(ERROR, TAG, "Error, Wrong status code: %d", status_code);
996 return CA_SOCKET_OPERATION_FAILED;
1001 return CA_STATUS_OK;
1004 static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock)
1006 VERIFY_NON_NULL_RET(sock, TAG, "sock", -1);
1008 if (OC_INVALID_SOCKET != sock->fd)
1010 OIC_LOG(DEBUG, TAG, "accept socket created already");
1014 socklen_t socklen = 0;
1015 struct sockaddr_storage server = { .ss_family = family };
1017 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
1018 if (OC_INVALID_SOCKET == fd)
1020 OIC_LOG(ERROR, TAG, "Failed to create socket");
1024 if (family == AF_INET6)
1026 // the socket is restricted to sending and receiving IPv6 packets only.
1028 //TODO: enable once IPv6 is supported
1030 if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
1032 OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
1036 ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port);
1037 socklen = sizeof (struct sockaddr_in6);
1041 ((struct sockaddr_in *)&server)->sin_port = htons(sock->port);
1042 socklen = sizeof (struct sockaddr_in);
1046 if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
1048 OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
1052 if (-1 == bind(fd, (struct sockaddr *)&server, socklen))
1054 OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
1058 if (listen(fd, caglobals.tcp.listenBacklog) != 0)
1060 OIC_LOG(ERROR, TAG, "listen() error");
1064 if (sock->port) // use the given port
1067 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof (on)))
1069 OIC_LOG_V(ERROR, TAG, "SO_REUSEADDR failed: %s", strerror(errno));
1071 return OC_INVALID_SOCKET;
1074 else // return the assigned port
1076 if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen))
1078 OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
1081 sock->port = ntohs(family == AF_INET6 ?
1082 ((struct sockaddr_in6 *)&server)->sin6_port :
1083 ((struct sockaddr_in *)&server)->sin_port);
1093 return OC_INVALID_SOCKET;
1096 static void CAInitializePipe(int *fds)
1098 int ret = pipe(fds);
1099 // TODO: Remove temporary workaround once F_GETFD / F_SETFD support is in TizenRT
1100 /* Temporary workaround: By pass F_GETFD / F_SETFD */
1110 OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
1115 ret = fcntl(fds[0], F_GETFD);
1118 ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
1122 ret = fcntl(fds[1], F_GETFD);
1126 ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
1136 OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
1142 #ifndef DISABLE_TCP_SERVER
1143 #define NEWSOCKET(FAMILY, NAME) \
1144 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
1145 if (caglobals.tcp.NAME.fd == -1) \
1147 caglobals.tcp.NAME.port = 0; \
1148 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
1151 void CATCPInitializeSocket()
1153 #ifndef __WITH_TLS__
1154 NEWSOCKET(AF_INET, ipv4);
1156 NEWSOCKET(AF_INET, ipv4s);
1159 //TODO Enable once TizenRT supports IPv6
1161 #ifndef __WITH_TLS__
1162 NEWSOCKET(AF_INET6, ipv6);
1164 NEWSOCKET(AF_INET6, ipv6s);
1167 #ifndef __WITH_TLS__
1168 OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
1169 caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
1170 OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
1171 caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
1173 OIC_LOG_V(DEBUG, TAG, "IPv4 secure socket fd=%d, port=%d",
1174 caglobals.tcp.ipv4s.fd, caglobals.tcp.ipv4s.port);
1175 OIC_LOG_V(DEBUG, TAG, "IPv6 secure socket fd=%d, port=%d",
1176 caglobals.tcp.ipv6s.fd, caglobals.tcp.ipv6s.port);
1179 #endif // DISABLE_TCP_SERVER
1181 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
1183 oc_mutex_lock(g_mutexObjectList);
1184 if (caglobals.tcp.started)
1186 oc_mutex_unlock(g_mutexObjectList);
1187 OIC_LOG(INFO, TAG, "Adapter is started already");
1188 return CA_STATUS_OK;
1191 g_threadPool = threadPool;
1193 if (!caglobals.tcp.ipv4tcpenabled)
1195 caglobals.tcp.ipv4tcpenabled = true; // only needed to run CA tests
1197 if (!caglobals.tcp.ipv6tcpenabled)
1199 caglobals.tcp.ipv6tcpenabled = true; // only needed to run CA tests
1202 caglobals.tcp.terminate = false;
1203 if (!caglobals.tcp.svrlist)
1205 caglobals.tcp.svrlist = u_arraylist_create();
1208 #ifndef DISABLE_TCP_SERVER
1209 if (caglobals.server)
1211 CATCPInitializeSocket();
1216 // create pipe for fast shutdown
1217 CAInitializePipe(caglobals.tcp.shutdownFds);
1219 // create pipe for connection event
1220 CAInitializePipe(caglobals.tcp.connectionFds);
1222 CAResult_t res = CA_STATUS_OK;
1224 res = ca_thread_pool_add_task(g_threadPool, CAReceiveHandler, NULL, &g_taskId);
1226 res = ca_thread_pool_add_task(g_threadPool, CAReceiveHandler, NULL, NULL,
1227 "IoT_TCPReceive", CONFIG_IOTIVITY_TCPRECEIVE_PTHREAD_STACKSIZE);
1229 if (CA_STATUS_OK != res)
1231 oc_mutex_unlock(g_mutexObjectList);
1232 OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
1237 caglobals.tcp.started = true;
1238 oc_mutex_unlock(g_mutexObjectList);
1240 OIC_LOG(INFO, TAG, "CAReceiveHandler thread started successfully.");
1241 return CA_STATUS_OK;
1244 void CATCPStopServer()
1246 oc_mutex_lock(g_mutexObjectList);
1247 if (caglobals.tcp.terminate)
1249 oc_mutex_unlock(g_mutexObjectList);
1250 OIC_LOG(INFO, TAG, "Adapter is not enabled");
1254 // set terminate flag.
1255 caglobals.tcp.terminate = true;
1257 oc_mutex_lock(g_mutexSend);
1258 oc_cond_signal(g_condSend);
1259 oc_mutex_unlock(g_mutexSend);
1262 if (caglobals.tcp.started)
1264 oc_cond_wait(g_condObjectList, g_mutexObjectList);
1265 caglobals.tcp.started = false;
1269 // close accept socket.
1270 #ifndef __WITH_TLS__
1274 CLOSE_SOCKET(ipv4s);
1275 CLOSE_SOCKET(ipv6s);
1278 if (caglobals.tcp.connectionFds[1] != OC_INVALID_SOCKET)
1280 close(caglobals.tcp.connectionFds[1]);
1281 caglobals.tcp.connectionFds[1] = OC_INVALID_SOCKET;
1283 if (caglobals.tcp.connectionFds[0] != OC_INVALID_SOCKET)
1285 close(caglobals.tcp.connectionFds[0]);
1286 caglobals.tcp.connectionFds[0] = OC_INVALID_SOCKET;
1289 if (caglobals.tcp.shutdownFds[1] != OC_INVALID_SOCKET)
1291 close(caglobals.tcp.shutdownFds[1]);
1292 caglobals.tcp.shutdownFds[1] = OC_INVALID_SOCKET;
1293 // receive thread will stop immediately
1295 if (caglobals.tcp.started)
1297 oc_cond_wait(g_condObjectList, g_mutexObjectList);
1298 caglobals.tcp.started = false;
1300 if (caglobals.tcp.shutdownFds[0] != OC_INVALID_SOCKET)
1302 close(caglobals.tcp.shutdownFds[0]);
1303 caglobals.tcp.shutdownFds[0] = OC_INVALID_SOCKET;
1306 oc_mutex_unlock(g_mutexObjectList);
1309 ca_thread_pool_remove_task(g_threadPool, g_taskId);
1312 CATCPDisconnectAll();
1314 OIC_LOG(INFO, TAG, "Adapter terminated successfully");
1317 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
1319 g_packetReceivedCallback = callback;
1322 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
1324 g_connectionCallback = connHandler;
1327 size_t CACheckPayloadLengthFromHeader(const void *data, size_t dlen)
1329 VERIFY_NON_NULL_RET(data, TAG, "data", -1);
1331 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1332 ((unsigned char *)data)[0] >> 4);
1334 coap_pdu_t *pdu = coap_new_pdu2(transport, dlen);
1337 OIC_LOG(ERROR, TAG, "outpdu is null");
1338 OIC_LOG_V(ERROR, TAG, "data length: %zu", dlen);
1342 int ret = coap_pdu_parse2((unsigned char *) data, dlen, pdu, transport);
1345 OIC_LOG(ERROR, TAG, "pdu parse failed");
1346 coap_delete_pdu(pdu);
1350 size_t payloadLen = 0;
1351 size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
1352 OIC_LOG_V(DEBUG, TAG, "headerSize : %zu, pdu length : %d",
1353 headerSize, pdu->length);
1354 if (pdu->length > headerSize)
1356 payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
1364 static ssize_t sendData(const CAEndpoint_t *endpoint, const void *data,
1365 size_t dlen, const char *fam)
1367 OIC_LOG_V(INFO, TAG, "The length of data that needs to be sent is %zu bytes", dlen);
1369 // #1. find a session info from list.
1370 CASocketFd_t sockFd = CAGetSocketFDFromEndpoint(endpoint);
1371 if (OC_INVALID_SOCKET == sockFd)
1373 // if there is no connection info, connect to remote device.
1374 sockFd = CAConnectTCPSession(endpoint);
1375 if (OC_INVALID_SOCKET == sockFd)
1377 OIC_LOG(ERROR, TAG, "Failed to create tcp session object");
1382 // #2. send data to remote device.
1383 ssize_t remainLen = dlen;
1384 unsigned int sendRetryTime = 1;
1388 ssize_t len = send(sockFd, data, remainLen, MSG_DONTWAIT | MSG_NOSIGNAL);
1390 ssize_t len = send(sockFd, data, remainLen, MSG_DONTWAIT);
1394 if (EWOULDBLOCK != errno && EAGAIN != errno)
1396 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
1397 CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
1398 len, false, strerror(errno));
1402 // re-trying send after 10, 20, 40, 80, 160 and 320 milliseconds
1403 if (sendRetryTime > 32)
1408 unsigned int waitTime = sendRetryTime * 10 * MILLISECONDS_PER_SECOND;
1409 OIC_LOG_V(WARNING, TAG, "send blocked. trying send after %u microseconds", waitTime);
1411 oc_mutex_lock(g_mutexSend);
1412 oc_cond_wait_for(g_condSend, g_mutexSend, waitTime);
1413 oc_mutex_unlock(g_mutexSend);
1415 oc_mutex_lock(g_mutexObjectList);
1416 if (caglobals.tcp.terminate)
1418 oc_mutex_unlock(g_mutexObjectList);
1421 oc_mutex_unlock(g_mutexObjectList);
1423 sendRetryTime = (sendRetryTime << 1);
1430 } while (remainLen > 0);
1435 OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
1436 CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
1441 ssize_t CATCPSendData(CAEndpoint_t *endpoint, const void *data, size_t datalen)
1443 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", -1);
1444 VERIFY_NON_NULL_RET(data, TAG, "data is NULL", -1);
1446 if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
1448 return sendData(endpoint, data, datalen, "ipv6");
1450 if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
1452 return sendData(endpoint, data, datalen, "ipv4");
1455 OIC_LOG(ERROR, TAG, "Not supported transport flags");
1459 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1461 VERIFY_NON_NULL(info, TAG, "info is NULL");
1462 VERIFY_NON_NULL(size, TAG, "size is NULL");
1464 return CA_NOT_SUPPORTED;
1467 CASocketFd_t CAConnectTCPSession(const CAEndpoint_t *endpoint)
1469 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1471 // #1. create TCP server object
1472 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
1475 OIC_LOG(ERROR, TAG, "Out of memory");
1476 return OC_INVALID_SOCKET;
1478 memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
1479 svritem->sep.endpoint.adapter = endpoint->adapter;
1480 svritem->sep.endpoint.port = endpoint->port;
1481 svritem->sep.endpoint.flags = endpoint->flags;
1482 svritem->sep.endpoint.ifindex = endpoint->ifindex;
1483 svritem->state = CONNECTING;
1484 svritem->isClient = true;
1486 // Allocate message buffer
1487 svritem->tlsdata = (unsigned char*) OICCalloc(TLS_DATA_MAX_SIZE, sizeof(unsigned char));
1488 if (!svritem->tlsdata)
1490 OIC_LOG(ERROR, TAG, "Out of memory");
1492 return OC_INVALID_SOCKET;
1495 // #2. add TCP connection info to list
1496 oc_mutex_lock(g_mutexObjectList);
1497 if (caglobals.tcp.svrlist)
1499 bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
1502 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
1504 OICFree(svritem->tlsdata);
1506 oc_mutex_unlock(g_mutexObjectList);
1507 return OC_INVALID_SOCKET;
1510 oc_mutex_unlock(g_mutexObjectList);
1512 // #3. create the socket and connect to TCP server
1513 int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
1514 if (CA_STATUS_OK != CATCPCreateSocket(family, svritem))
1516 return OC_INVALID_SOCKET;
1519 // #4. pass the connection information to CA Common Layer.
1520 if (g_connectionCallback)
1522 g_connectionCallback(&(svritem->sep.endpoint), true, svritem->isClient);
1528 CAResult_t CADisconnectTCPSession(size_t index)
1530 CATCPSessionInfo_t *removedData = u_arraylist_remove(caglobals.tcp.svrlist, index);
1533 OIC_LOG(DEBUG, TAG, "there is no data to be removed");
1534 return CA_STATUS_OK;
1537 // close the socket and remove session info in list.
1538 if (removedData->fd >= 0)
1540 shutdown(removedData->fd, SHUT_RDWR);
1541 close(removedData->fd);
1542 removedData->fd = -1;
1543 removedData->state = (CONNECTED == removedData->state) ?
1544 DISCONNECTED : removedData->state;
1546 // pass the connection information to CA Common Layer.
1547 if (g_connectionCallback && DISCONNECTED == removedData->state)
1549 g_connectionCallback(&(removedData->sep.endpoint), false, removedData->isClient);
1552 OICFree(removedData->data);
1553 removedData->data = NULL;
1555 OICFree(removedData->tlsdata);
1556 removedData->tlsdata = NULL;
1558 OICFree(removedData);
1561 OIC_LOG(DEBUG, TAG, "data is removed from session list");
1563 #ifndef DISABLE_TCP_SERVER
1564 if (caglobals.server && MAX_CONNECTION_COUNTS == u_arraylist_length(caglobals.tcp.svrlist) + 1)
1566 CATCPInitializeSocket();
1570 return CA_STATUS_OK;
1573 void CATCPDisconnectAll()
1575 OIC_LOG(DEBUG, TAG, "IN - CATCPDisconnectAll");
1577 oc_mutex_lock(g_mutexObjectList);
1579 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1580 for (ssize_t index = length; index > 0; index--)
1582 // disconnect session from remote device.
1583 CADisconnectTCPSession(index - 1);
1586 u_arraylist_destroy(caglobals.tcp.svrlist);
1587 caglobals.tcp.svrlist = NULL;
1589 oc_mutex_unlock(g_mutexObjectList);
1592 CAcloseSslConnectionAll(CA_ADAPTER_TCP);
1595 OIC_LOG(DEBUG, TAG, "OUT - CATCPDisconnectAll");
1598 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
1600 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1601 VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
1603 OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1605 // get connection info from list
1606 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1607 for (size_t i = 0; i < length; i++)
1609 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1610 caglobals.tcp.svrlist, i);
1616 if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1617 sizeof(svritem->sep.endpoint.addr))
1618 && (svritem->sep.endpoint.port == endpoint->port)
1619 && (svritem->sep.endpoint.flags & endpoint->flags))
1621 OIC_LOG(DEBUG, TAG, "Found in session list");
1627 OIC_LOG(DEBUG, TAG, "Session not found");
1631 CASocketFd_t CAGetSocketFDFromEndpoint(const CAEndpoint_t *endpoint)
1633 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1635 OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1637 // get connection info from list.
1638 oc_mutex_lock(g_mutexObjectList);
1639 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1640 for (size_t i = 0; i < length; i++)
1642 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1643 caglobals.tcp.svrlist, i);
1649 if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1650 sizeof(svritem->sep.endpoint.addr))
1651 && (svritem->sep.endpoint.port == endpoint->port)
1652 && (svritem->sep.endpoint.flags & endpoint->flags))
1654 oc_mutex_unlock(g_mutexObjectList);
1655 OIC_LOG(DEBUG, TAG, "Found in session list");
1660 oc_mutex_unlock(g_mutexObjectList);
1661 OIC_LOG(DEBUG, TAG, "Session not found");
1662 return OC_INVALID_SOCKET;
1665 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1668 // check from the last item.
1669 CATCPSessionInfo_t *svritem = NULL;
1670 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1671 for (size_t i = 0; i < length; i++)
1673 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1675 if (svritem && svritem->fd == fd)
1678 oc_mutex_unlock(g_mutexObjectList);
1687 static CATCPSessionInfo_t *CAGetSessionInfoFromFDAsOwner(int fd, size_t *index)
1689 CATCPSessionInfo_t *svritem = NULL;
1690 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1691 for (size_t i = 0; i < length; i++)
1693 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1695 if (svritem && svritem->fd == fd)
1705 CAResult_t CASearchAndDeleteTCPSession(const CAEndpoint_t *endpoint)
1707 oc_mutex_lock(g_mutexObjectList);
1709 CAResult_t result = CA_STATUS_OK;
1711 CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1714 result = CADisconnectTCPSession(index);
1715 if (CA_STATUS_OK != result)
1717 OIC_LOG_V(ERROR, TAG, "CADisconnectTCPSession failed, result[%d]", result);
1721 oc_mutex_unlock(g_mutexObjectList);
1725 void CATCPCloseInProgressConnections()
1727 OIC_LOG(INFO, TAG, "IN - CATCPCloseInProgressConnections");
1729 oc_mutex_lock(g_mutexObjectList);
1731 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1732 for (size_t index = 0; index < length; index++)
1734 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1735 caglobals.tcp.svrlist, index);
1741 // Session which are connecting state
1742 if (svritem->fd >= 0 && svritem->state == CONNECTING)
1744 shutdown(svritem->fd, SHUT_RDWR);
1747 svritem->state = DISCONNECTED;
1751 oc_mutex_unlock(g_mutexObjectList);
1753 OIC_LOG(INFO, TAG, "OUT - CATCPCloseInProgressConnections");
1756 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1758 OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1760 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1761 ((unsigned char *)recvBuffer)[0] >> 4);
1762 size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1764 size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1766 OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%zu]", optPaylaodLen);
1767 OIC_LOG_V(DEBUG, TAG, "header length [%zu]", headerLen);
1768 OIC_LOG_V(DEBUG, TAG, "total data length [%zu]", headerLen + optPaylaodLen);
1770 OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1771 return headerLen + optPaylaodLen;
1774 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1776 g_tcpErrorHandler = errorHandleCallback;