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);
334 int ret = poll(readFds, counter, timeout);
336 oc_mutex_lock(g_mutexObjectList);
337 if (caglobals.tcp.terminate)
339 OIC_LOG_V(INFO, TAG, "Packet receiver Stop request received.");
340 oc_mutex_unlock(g_mutexObjectList);
344 oc_mutex_unlock(g_mutexObjectList);
348 CAPollReturned(readFds, counter);
352 OIC_LOG_V(FATAL, TAG, "poll error %s", strerror(errno));
358 static void CAPollReturned(struct pollfd *readFds, size_t size)
360 VERIFY_NON_NULL_VOID(readFds, TAG, "readFds is NULL");
362 if (caglobals.tcp.ipv4.fd != -1 && readFds[0].revents == POLLIN)
364 CAAcceptConnection(CA_IPV4, &caglobals.tcp.ipv4);
367 else if (caglobals.tcp.ipv4s.fd != -1 && readFds[1].revents == POLLIN)
369 CAAcceptConnection(CA_IPV4 | CA_SECURE, &caglobals.tcp.ipv4s);
372 else if (caglobals.tcp.ipv6.fd != -1 && readFds[2].revents == POLLIN)
374 CAAcceptConnection(CA_IPV6, &caglobals.tcp.ipv6);
377 else if (caglobals.tcp.ipv6s.fd != -1 && readFds[3].revents == POLLIN)
379 CAAcceptConnection(CA_IPV6 | CA_SECURE, &caglobals.tcp.ipv6s);
382 else if (-1 != caglobals.tcp.connectionFds[0] && readFds[4].revents != 0)
384 // new connection was created from remote device.
385 // exit the function to update read file descriptor.
386 char buf[MAX_ADDR_STR_SIZE_CA] = {0};
387 ssize_t len = read(caglobals.tcp.connectionFds[0], buf, sizeof (buf));
392 OIC_LOG_V(DEBUG, TAG, "Received new connection event with [%s]", buf);
397 int *readFDList = NULL;
398 size_t readFDListSize = 0;
400 oc_mutex_lock(g_mutexObjectList);
401 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
403 readFDList = (int*) OICCalloc(length, sizeof(int));
404 if (NULL == readFDList)
406 OIC_LOG_V(ERROR, TAG, "Failed to allocate memory!");
407 oc_mutex_unlock(g_mutexObjectList);
411 for (size_t i = 0; i < length; i++)
413 CATCPSessionInfo_t *svritem =
414 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
415 if (svritem && svritem->fd >= 0)
420 if (svritem->fd == readFds[j].fd)
427 if (j < size && readFds[j].revents != 0)
429 readFDList[readFDListSize++] = svritem->fd;
433 oc_mutex_unlock(g_mutexObjectList);
435 // Read incomming messages from fds
436 for (size_t i = 0; i < readFDListSize; i++)
438 CAReceiveMessage(readFDList[i]);
445 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock)
447 OIC_LOG_V(INFO, TAG, "In %s", __func__);
448 VERIFY_NON_NULL_VOID(sock, TAG, "sock is NULL");
450 if (MAX_CONNECTION_COUNTS == u_arraylist_length(caglobals.tcp.svrlist))
452 OIC_LOG_V(INFO, TAG, "Exceeding the max connection counts limit, close listening port");
454 sock->fd = OC_INVALID_SOCKET;
458 struct sockaddr_storage clientaddr;
459 socklen_t clientlen = sizeof (struct sockaddr_in);
462 clientlen = sizeof(struct sockaddr_in6);
465 CASocketFd_t sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen);
466 if (OC_INVALID_SOCKET != sockfd)
468 CATCPSessionInfo_t *svritem =
469 (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
472 OIC_LOG(ERROR, TAG, "Out of memory");
477 svritem->fd = sockfd;
478 svritem->sep.endpoint.flags = flag;
479 svritem->sep.endpoint.adapter = CA_ADAPTER_TCP;
480 svritem->state = CONNECTED;
481 svritem->isClient = false;
482 CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
483 svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
485 // Allocate message buffer
486 svritem->tlsdata = (unsigned char*) OICCalloc(TLS_DATA_MAX_SIZE, sizeof(unsigned char));
487 if (!svritem->tlsdata)
489 OIC_LOG(ERROR, TAG, "Out of memory");
495 oc_mutex_lock(g_mutexObjectList);
496 bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem);
499 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
501 OICFree(svritem->tlsdata);
503 oc_mutex_unlock(g_mutexObjectList);
506 oc_mutex_unlock(g_mutexObjectList);
508 // pass the connection information to CA Common Layer.
509 if (g_connectionCallback)
511 g_connectionCallback(&(svritem->sep.endpoint), true, svritem->isClient);
514 OIC_LOG_V(INFO, TAG, "Out %s", __func__);
518 * Clean socket state data
520 * @param[in/out] item - socket state data
522 void CACleanData(CATCPSessionInfo_t *svritem)
526 OICFree(svritem->data);
527 svritem->data = NULL;
532 svritem->totalLen = 0;
534 svritem->protocol = UNKNOWN;
539 * Construct CoAP header and payload from buffer
541 * @param[in] svritem - used socket, buffer, current received message length and protocol
542 * @param[in/out] data - data buffer, this value is updated as data is copied to svritem
543 * @param[in/out] dataLength - length of data, this value decreased as data is copied to svritem
544 * @return - CA_STATUS_OK or appropriate error code
546 CAResult_t CAConstructCoAP(CATCPSessionInfo_t *svritem, unsigned char **data,
549 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
551 if (NULL == svritem || NULL == data || NULL == dataLength)
553 OIC_LOG(ERROR, TAG, "Invalid input parameter(NULL)");
554 return CA_STATUS_INVALID_PARAM;
557 unsigned char *inBuffer = *data;
558 size_t inLen = *dataLength;
559 OIC_LOG_V(DEBUG, TAG, "before-datalength : %zd", *dataLength);
561 if (NULL == svritem->data && inLen > 0)
563 // allocate memory for message header (CoAP header size because it is bigger)
564 svritem->data = (unsigned char *) OICCalloc(1, COAP_MAX_HEADER_SIZE);
565 if (NULL == svritem->data)
567 OIC_LOG(ERROR, TAG, "OICCalloc - out of memory");
568 return CA_MEMORY_ALLOC_FAILED;
571 // copy 1 byte to parse coap header length
572 memcpy(svritem->data, inBuffer, 1);
574 svritem->bufLen = COAP_MAX_HEADER_SIZE;
579 //if not enough data received - read them on next CAFillHeader() call
585 //if enough data received - parse header
586 svritem->protocol = COAP;
588 //seems CoAP data received. read full coap header.
589 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(svritem->data[0] >> 4);
590 size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
594 if (svritem->len < headerLen)
596 copyLen = headerLen - svritem->len;
602 //read required bytes to have full CoAP header
603 memcpy(svritem->data + svritem->len, inBuffer, copyLen);
604 svritem->len += copyLen;
608 //if not enough data received - read them on next CAFillHeader() call
609 if (svritem->len < headerLen)
613 OIC_LOG(DEBUG, TAG, "CoAP header received partially. Wait for rest header data");
617 //calculate CoAP message length
618 svritem->totalLen = CAGetTotalLengthFromHeader(svritem->data);
624 // Calculate length of data to be copied.
625 copyLen = svritem->totalLen - svritem->len;
631 // Is buffer not big enough for remaining data ?
632 if (svritem->len + copyLen > svritem->bufLen)
634 // Resize buffer to accommodate enough space
635 size_t extLen = svritem->totalLen - svritem->bufLen;
636 if (extLen > COAP_TCP_MAX_BUFFER_CHUNK_SIZE)
638 extLen = COAP_TCP_MAX_BUFFER_CHUNK_SIZE;
641 // Allocate required memory
642 unsigned char *buffer = OICRealloc(svritem->data, svritem->bufLen + extLen);
645 OIC_LOG(ERROR, TAG, "OICRealloc - out of memory");
646 return CA_MEMORY_ALLOC_FAILED;
649 svritem->data = buffer;
650 svritem->bufLen += extLen;
653 // Read required bytes to have full CoAP payload
654 memcpy(svritem->data + svritem->len, inBuffer, copyLen);
655 svritem->len += copyLen;
663 OIC_LOG_V(DEBUG, TAG, "after-datalength : %zd", *dataLength);
664 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
668 static void CAReceiveMessage(int fd)
670 CAResult_t res = CA_STATUS_OK;
672 oc_mutex_lock(g_mutexObjectList);
674 //get remote device information from file descriptor.
676 CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFDAsOwner(fd, &index);
679 OIC_LOG(ERROR, TAG, "there is no connection information in list");
680 oc_mutex_unlock(g_mutexObjectList);
684 CASecureEndpoint_t peerEP = svritem->sep;
686 if (svritem->sep.endpoint.flags & CA_SECURE) // Secure connection
688 svritem->protocol = TLS;
692 size_t tlsLength = 0;
694 if (TLS_HEADER_SIZE > svritem->tlsLen)
696 nbRead = TLS_HEADER_SIZE - svritem->tlsLen;
700 //[3][4] bytes in tls header are tls payload length
701 tlsLength = TLS_HEADER_SIZE +
702 (size_t)((svritem->tlsdata[3] << 8) | svritem->tlsdata[4]);
703 OIC_LOG_V(DEBUG, TAG, "total tls length = %zd", tlsLength);
704 if (tlsLength > TLS_DATA_MAX_SIZE)
706 OIC_LOG_V(ERROR, TAG, "total tls length is too big (buffer size : %u)",
708 oc_mutex_unlock(g_mutexObjectList);
709 CATCPDisconnectSession(&peerEP.endpoint);
712 nbRead = tlsLength - svritem->tlsLen;
715 len = recv(fd, svritem->tlsdata + svritem->tlsLen, nbRead, 0);
718 OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno));
719 res = CA_RECEIVE_FAILED;
723 OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
724 svritem->state = DISCONNECTED;
725 res = CA_DESTINATION_DISCONNECTED;
729 svritem->tlsLen += len;
730 OIC_LOG_V(DEBUG, TAG, "nb_read : %zd bytes , recv() : %d bytes, svritem->tlsLen : %zd bytes",
731 nbRead, len, svritem->tlsLen);
732 if (tlsLength > 0 && tlsLength == svritem->tlsLen)
734 // When successfully read data - pass them to callback.
735 // Dont invoke callback locking mutex
736 unsigned char *mesBuf = svritem->tlsdata;
737 size_t mesBufLen = svritem->tlsLen;
738 svritem->tlsdata = NULL;
739 oc_mutex_unlock(g_mutexObjectList);
741 res = CAdecryptSsl(&peerEP, (uint8_t *)mesBuf, mesBufLen);
742 OIC_LOG_V(INFO, TAG, "%s: CAdecryptSsl returned %d", __func__, res);
744 // Check for the svritem and reset buffer
745 oc_mutex_lock(g_mutexObjectList);
746 svritem = CAGetSessionInfoFromFDAsOwner(fd, &index);
749 svritem->tlsdata = mesBuf;
754 // svritem does not exist, thus free the message buffer
755 OIC_LOG(ERROR, TAG, "svritem not found. Freeing message buffer!");
762 else // Non-Secure connection
764 svritem->protocol = COAP;
766 // svritem->tlsdata can also be used as receiving buffer in case of raw tcp
767 len = recv(fd, svritem->tlsdata, TLS_DATA_MAX_SIZE, 0);
770 OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno));
771 res = CA_RECEIVE_FAILED;
775 OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
776 res = CA_DESTINATION_DISCONNECTED;
780 //when successfully read data - pass them to callback.
781 OIC_LOG_V(DEBUG, TAG, "recv() : %d bytes", len);
782 if (g_packetReceivedCallback)
784 // Dont invoke callback locking mutex
785 unsigned char *mesBuf = svritem->tlsdata;
786 svritem->tlsdata = NULL;
787 oc_mutex_unlock(g_mutexObjectList);
789 res = g_packetReceivedCallback(&peerEP, mesBuf, len);
791 // Check for the svritem and reset buffer
792 oc_mutex_lock(g_mutexObjectList);
793 svritem = CAGetSessionInfoFromFDAsOwner(fd, &index);
796 svritem->tlsdata = mesBuf;
801 // svritem does not exist, thus free the message buffer
802 OIC_LOG(ERROR, TAG, "svritem not found. Freeing message buffer!");
809 oc_mutex_unlock(g_mutexObjectList);
811 if (res != CA_STATUS_OK)
813 CATCPDisconnectSession(&peerEP.endpoint);
817 static ssize_t CAWakeUpForReadFdsUpdate(const char *host)
819 if (caglobals.tcp.connectionFds[1] != -1)
824 len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
825 } while ((len == -1) && (errno == EINTR));
827 if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
829 OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
836 static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port,
837 struct sockaddr_storage *sockaddr)
839 struct addrinfo *addrs = NULL;
840 struct addrinfo hints = { .ai_family = family,
841 .ai_protocol = IPPROTO_TCP,
842 .ai_socktype = SOCK_STREAM,
843 .ai_flags = AI_NUMERICHOST };
845 int r = getaddrinfo(host, NULL, &hints, &addrs);
850 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: errno %s", strerror(errno));
854 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: %s", gai_strerror(r));
857 return CA_STATUS_FAILED;
859 // assumption: in this case, getaddrinfo will only return one addrinfo
860 // or first is the one we want.
861 if (addrs[0].ai_family == AF_INET6)
863 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6));
864 ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port);
868 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in));
869 ((struct sockaddr_in *)sockaddr)->sin_port = htons(port);
875 #if defined(__TIZEN__)
876 static int CAGetHTTPStatusCode(char * response) {
877 char *resp, *code_plus, *ptrSave;
880 resp = strdup(response);
881 strtok_r(resp, " ", &ptrSave); /* skip HTTP version */
882 code_plus = strtok_r(NULL, " ", &ptrSave);
884 ret = code_plus ? atoi(code_plus) : -1;
890 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
892 VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
894 OIC_LOG_V(INFO, TAG, "try to connect with [%s:%u]",
895 svritem->sep.endpoint.addr, svritem->sep.endpoint.port);
897 // #1. create tcp socket.
898 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
901 OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
902 return CA_SOCKET_OPERATION_FAILED;
906 // #2. convert address from string to binary.
907 struct sockaddr_storage sa = { .ss_family = family };
908 CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr,
909 svritem->sep.endpoint.port, &sa);
910 if (CA_STATUS_OK != res)
912 OIC_LOG(ERROR, TAG, "convert name to sockaddr failed");
913 return CA_SOCKET_OPERATION_FAILED;
916 // #3. set socket length.
917 socklen_t socklen = 0;
918 if (sa.ss_family == AF_INET6)
920 struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
921 if (!sock6->sin6_scope_id)
923 sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
925 socklen = sizeof(struct sockaddr_in6);
929 socklen = sizeof(struct sockaddr_in);
932 // #4. connect to remote server device.
933 if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
935 OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
936 CALogSendStateInfo(svritem->sep.endpoint.adapter, svritem->sep.endpoint.addr,
937 svritem->sep.endpoint.port, 0, false, strerror(errno));
938 return CA_SOCKET_OPERATION_FAILED;
941 OIC_LOG(INFO, TAG, "connect socket success");
942 svritem->state = CONNECTED;
943 ssize_t len = CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
946 OIC_LOG(ERROR, TAG, "wakeup receive thread failed");
947 return CA_SOCKET_OPERATION_FAILED;
950 #if defined(__TIZEN__)
951 // #5. Send HTTP CONNECT to proxy if proxy
953 const char *cloud_address = CAGetCloudAddressForProxy();
954 OIC_LOG_V(INFO, TAG, "Proxy : '%s'", cloud_address ? cloud_address : "(nil)");
956 if(cloud_address && *cloud_address)
959 int len = sprintf(message,
960 "CONNECT %s HTTP/1.1\r\n"
961 "Host: %s\r\n\r\n", cloud_address, cloud_address
964 ssize_t l = send(fd, message, len, 0);
967 OIC_LOG_V(ERROR, TAG, "failed to send HTTP CONNECT data (expected %d bytes, ret %zd)", len, l);
970 return CA_SOCKET_OPERATION_FAILED;
973 // maybe this should be called in other thread, it causes bottleneck.
974 OIC_LOG_V(INFO, TAG, "Message sent is : '%s'\n", message);
977 OIC_LOG_V(INFO, TAG, "Receiving response to CONNECT from proxy...");
979 l = recv(fd, message, 4096, 0);
981 OIC_LOG_V(INFO, TAG, "Received data : '%s'", message);
982 OIC_LOG_V(INFO, TAG, "Received len = %zd", l);
984 int status_code = CAGetHTTPStatusCode(message);
986 OIC_LOG_V(INFO, TAG, "HTTP status_code : %d", status_code);
987 if(status_code < 200 || status_code > 299)
989 OIC_LOG_V(ERROR, TAG, "Error, Wrong status code: %d", status_code);
992 return CA_SOCKET_OPERATION_FAILED;
1000 static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock)
1002 VERIFY_NON_NULL_RET(sock, TAG, "sock", -1);
1004 if (OC_INVALID_SOCKET != sock->fd)
1006 OIC_LOG(DEBUG, TAG, "accept socket created already");
1010 socklen_t socklen = 0;
1011 struct sockaddr_storage server = { .ss_family = family };
1013 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
1014 if (OC_INVALID_SOCKET == fd)
1016 OIC_LOG(ERROR, TAG, "Failed to create socket");
1020 if (family == AF_INET6)
1022 // the socket is restricted to sending and receiving IPv6 packets only.
1024 //TODO: enable once IPv6 is supported
1026 if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
1028 OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
1032 ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port);
1033 socklen = sizeof (struct sockaddr_in6);
1037 ((struct sockaddr_in *)&server)->sin_port = htons(sock->port);
1038 socklen = sizeof (struct sockaddr_in);
1042 if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
1044 OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
1048 if (-1 == bind(fd, (struct sockaddr *)&server, socklen))
1050 OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
1054 if (listen(fd, caglobals.tcp.listenBacklog) != 0)
1056 OIC_LOG(ERROR, TAG, "listen() error");
1060 if (sock->port) // use the given port
1063 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof (on)))
1065 OIC_LOG_V(ERROR, TAG, "SO_REUSEADDR failed: %s", strerror(errno));
1067 return OC_INVALID_SOCKET;
1070 else // return the assigned port
1072 if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen))
1074 OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
1077 sock->port = ntohs(family == AF_INET6 ?
1078 ((struct sockaddr_in6 *)&server)->sin6_port :
1079 ((struct sockaddr_in *)&server)->sin_port);
1089 return OC_INVALID_SOCKET;
1092 static void CAInitializePipe(int *fds)
1094 int ret = pipe(fds);
1095 // TODO: Remove temporary workaround once F_GETFD / F_SETFD support is in TizenRT
1096 /* Temporary workaround: By pass F_GETFD / F_SETFD */
1106 OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
1111 ret = fcntl(fds[0], F_GETFD);
1114 ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
1118 ret = fcntl(fds[1], F_GETFD);
1122 ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
1132 OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
1138 #ifndef DISABLE_TCP_SERVER
1139 #define NEWSOCKET(FAMILY, NAME) \
1140 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
1141 if (caglobals.tcp.NAME.fd == -1) \
1143 caglobals.tcp.NAME.port = 0; \
1144 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
1147 void CATCPInitializeSocket()
1149 #ifndef __WITH_TLS__
1150 NEWSOCKET(AF_INET, ipv4);
1152 NEWSOCKET(AF_INET, ipv4s);
1155 //TODO Enable once TizenRT supports IPv6
1157 #ifndef __WITH_TLS__
1158 NEWSOCKET(AF_INET6, ipv6);
1160 NEWSOCKET(AF_INET6, ipv6s);
1163 #ifndef __WITH_TLS__
1164 OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
1165 caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
1166 OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
1167 caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
1169 OIC_LOG_V(DEBUG, TAG, "IPv4 secure socket fd=%d, port=%d",
1170 caglobals.tcp.ipv4s.fd, caglobals.tcp.ipv4s.port);
1171 OIC_LOG_V(DEBUG, TAG, "IPv6 secure socket fd=%d, port=%d",
1172 caglobals.tcp.ipv6s.fd, caglobals.tcp.ipv6s.port);
1175 #endif // DISABLE_TCP_SERVER
1177 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
1179 oc_mutex_lock(g_mutexObjectList);
1180 if (caglobals.tcp.started)
1182 oc_mutex_unlock(g_mutexObjectList);
1183 OIC_LOG(INFO, TAG, "Adapter is started already");
1184 return CA_STATUS_OK;
1187 g_threadPool = threadPool;
1189 if (!caglobals.tcp.ipv4tcpenabled)
1191 caglobals.tcp.ipv4tcpenabled = true; // only needed to run CA tests
1193 if (!caglobals.tcp.ipv6tcpenabled)
1195 caglobals.tcp.ipv6tcpenabled = true; // only needed to run CA tests
1198 caglobals.tcp.terminate = false;
1199 if (!caglobals.tcp.svrlist)
1201 caglobals.tcp.svrlist = u_arraylist_create();
1204 #ifndef DISABLE_TCP_SERVER
1205 if (caglobals.server)
1207 CATCPInitializeSocket();
1212 // create pipe for fast shutdown
1213 CAInitializePipe(caglobals.tcp.shutdownFds);
1215 // create pipe for connection event
1216 CAInitializePipe(caglobals.tcp.connectionFds);
1218 CAResult_t res = CA_STATUS_OK;
1220 res = ca_thread_pool_add_task(g_threadPool, CAReceiveHandler, NULL, &g_taskId);
1222 res = ca_thread_pool_add_task(g_threadPool, CAReceiveHandler, NULL, NULL,
1223 "IoT_TCPReceive", CONFIG_IOTIVITY_TCPRECEIVE_PTHREAD_STACKSIZE);
1225 if (CA_STATUS_OK != res)
1227 oc_mutex_unlock(g_mutexObjectList);
1228 OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
1233 caglobals.tcp.started = true;
1234 oc_mutex_unlock(g_mutexObjectList);
1236 OIC_LOG(INFO, TAG, "CAReceiveHandler thread started successfully.");
1237 return CA_STATUS_OK;
1240 void CATCPStopServer()
1242 oc_mutex_lock(g_mutexObjectList);
1243 if (caglobals.tcp.terminate)
1245 oc_mutex_unlock(g_mutexObjectList);
1246 OIC_LOG(INFO, TAG, "Adapter is not enabled");
1250 // set terminate flag.
1251 caglobals.tcp.terminate = true;
1253 oc_mutex_lock(g_mutexSend);
1254 oc_cond_signal(g_condSend);
1255 oc_mutex_unlock(g_mutexSend);
1258 if (caglobals.tcp.started)
1260 oc_cond_wait(g_condObjectList, g_mutexObjectList);
1261 caglobals.tcp.started = false;
1265 // close accept socket.
1266 #ifndef __WITH_TLS__
1270 CLOSE_SOCKET(ipv4s);
1271 CLOSE_SOCKET(ipv6s);
1274 if (caglobals.tcp.connectionFds[1] != OC_INVALID_SOCKET)
1276 close(caglobals.tcp.connectionFds[1]);
1277 caglobals.tcp.connectionFds[1] = OC_INVALID_SOCKET;
1279 if (caglobals.tcp.connectionFds[0] != OC_INVALID_SOCKET)
1281 close(caglobals.tcp.connectionFds[0]);
1282 caglobals.tcp.connectionFds[0] = OC_INVALID_SOCKET;
1285 if (caglobals.tcp.shutdownFds[1] != OC_INVALID_SOCKET)
1287 close(caglobals.tcp.shutdownFds[1]);
1288 caglobals.tcp.shutdownFds[1] = OC_INVALID_SOCKET;
1289 // receive thread will stop immediately
1291 if (caglobals.tcp.started)
1293 oc_cond_wait(g_condObjectList, g_mutexObjectList);
1294 caglobals.tcp.started = false;
1296 if (caglobals.tcp.shutdownFds[0] != OC_INVALID_SOCKET)
1298 close(caglobals.tcp.shutdownFds[0]);
1299 caglobals.tcp.shutdownFds[0] = OC_INVALID_SOCKET;
1302 oc_mutex_unlock(g_mutexObjectList);
1305 ca_thread_pool_remove_task(g_threadPool, g_taskId);
1308 CATCPDisconnectAll();
1310 OIC_LOG(INFO, TAG, "Adapter terminated successfully");
1313 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
1315 g_packetReceivedCallback = callback;
1318 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
1320 g_connectionCallback = connHandler;
1323 size_t CACheckPayloadLengthFromHeader(const void *data, size_t dlen)
1325 VERIFY_NON_NULL_RET(data, TAG, "data", -1);
1327 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1328 ((unsigned char *)data)[0] >> 4);
1330 coap_pdu_t *pdu = coap_new_pdu2(transport, dlen);
1333 OIC_LOG(ERROR, TAG, "outpdu is null");
1334 OIC_LOG_V(ERROR, TAG, "data length: %zu", dlen);
1338 int ret = coap_pdu_parse2((unsigned char *) data, dlen, pdu, transport);
1341 OIC_LOG(ERROR, TAG, "pdu parse failed");
1342 coap_delete_pdu(pdu);
1346 size_t payloadLen = 0;
1347 size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
1348 OIC_LOG_V(DEBUG, TAG, "headerSize : %zu, pdu length : %d",
1349 headerSize, pdu->length);
1350 if (pdu->length > headerSize)
1352 payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
1360 static ssize_t sendData(const CAEndpoint_t *endpoint, const void *data,
1361 size_t dlen, const char *fam)
1363 OIC_LOG_V(INFO, TAG, "The length of data that needs to be sent is %zu bytes", dlen);
1365 // #1. find a session info from list.
1366 CASocketFd_t sockFd = CAGetSocketFDFromEndpoint(endpoint);
1367 if (OC_INVALID_SOCKET == sockFd)
1369 // if there is no connection info, connect to remote device.
1370 sockFd = CAConnectTCPSession(endpoint);
1371 if (OC_INVALID_SOCKET == sockFd)
1373 OIC_LOG(ERROR, TAG, "Failed to create tcp session object");
1378 // #2. send data to remote device.
1379 ssize_t remainLen = dlen;
1380 unsigned int sendRetryTime = 1;
1384 ssize_t len = send(sockFd, data, remainLen, MSG_DONTWAIT | MSG_NOSIGNAL);
1386 ssize_t len = send(sockFd, data, remainLen, MSG_DONTWAIT);
1390 if (EWOULDBLOCK != errno && EAGAIN != errno)
1392 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno));
1393 CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
1394 len, false, strerror(errno));
1398 // re-trying send after 10, 20, 40, 80, 160 and 320 milliseconds
1399 if (sendRetryTime > 32)
1404 unsigned int waitTime = sendRetryTime * 10 * MILLISECONDS_PER_SECOND;
1405 OIC_LOG_V(WARNING, TAG, "send blocked. trying send after %u microseconds", waitTime);
1407 oc_mutex_lock(g_mutexSend);
1408 oc_cond_wait_for(g_condSend, g_mutexSend, waitTime);
1409 oc_mutex_unlock(g_mutexSend);
1411 oc_mutex_lock(g_mutexObjectList);
1412 if (caglobals.tcp.terminate)
1414 oc_mutex_unlock(g_mutexObjectList);
1417 oc_mutex_unlock(g_mutexObjectList);
1419 sendRetryTime = (sendRetryTime << 1);
1426 } while (remainLen > 0);
1431 OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
1432 CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
1437 ssize_t CATCPSendData(CAEndpoint_t *endpoint, const void *data, size_t datalen)
1439 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", -1);
1440 VERIFY_NON_NULL_RET(data, TAG, "data is NULL", -1);
1442 if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
1444 return sendData(endpoint, data, datalen, "ipv6");
1446 if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
1448 return sendData(endpoint, data, datalen, "ipv4");
1451 OIC_LOG(ERROR, TAG, "Not supported transport flags");
1455 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1457 VERIFY_NON_NULL(info, TAG, "info is NULL");
1458 VERIFY_NON_NULL(size, TAG, "size is NULL");
1460 return CA_NOT_SUPPORTED;
1463 CASocketFd_t CAConnectTCPSession(const CAEndpoint_t *endpoint)
1465 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1467 // #1. create TCP server object
1468 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
1471 OIC_LOG(ERROR, TAG, "Out of memory");
1472 return OC_INVALID_SOCKET;
1474 memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
1475 svritem->sep.endpoint.adapter = endpoint->adapter;
1476 svritem->sep.endpoint.port = endpoint->port;
1477 svritem->sep.endpoint.flags = endpoint->flags;
1478 svritem->sep.endpoint.ifindex = endpoint->ifindex;
1479 svritem->state = CONNECTING;
1480 svritem->isClient = true;
1482 // Allocate message buffer
1483 svritem->tlsdata = (unsigned char*) OICCalloc(TLS_DATA_MAX_SIZE, sizeof(unsigned char));
1484 if (!svritem->tlsdata)
1486 OIC_LOG(ERROR, TAG, "Out of memory");
1488 return OC_INVALID_SOCKET;
1491 // #2. add TCP connection info to list
1492 oc_mutex_lock(g_mutexObjectList);
1493 if (caglobals.tcp.svrlist)
1495 bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
1498 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
1500 OICFree(svritem->tlsdata);
1502 oc_mutex_unlock(g_mutexObjectList);
1503 return OC_INVALID_SOCKET;
1506 oc_mutex_unlock(g_mutexObjectList);
1508 // #3. create the socket and connect to TCP server
1509 int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
1510 if (CA_STATUS_OK != CATCPCreateSocket(family, svritem))
1512 return OC_INVALID_SOCKET;
1515 // #4. pass the connection information to CA Common Layer.
1516 if (g_connectionCallback)
1518 g_connectionCallback(&(svritem->sep.endpoint), true, svritem->isClient);
1524 CAResult_t CADisconnectTCPSession(size_t index)
1526 CATCPSessionInfo_t *removedData = u_arraylist_remove(caglobals.tcp.svrlist, index);
1529 OIC_LOG(DEBUG, TAG, "there is no data to be removed");
1530 return CA_STATUS_OK;
1533 // close the socket and remove session info in list.
1534 if (removedData->fd >= 0)
1536 shutdown(removedData->fd, SHUT_RDWR);
1537 close(removedData->fd);
1538 removedData->fd = -1;
1539 removedData->state = (CONNECTED == removedData->state) ?
1540 DISCONNECTED : removedData->state;
1542 // pass the connection information to CA Common Layer.
1543 if (g_connectionCallback && DISCONNECTED == removedData->state)
1545 g_connectionCallback(&(removedData->sep.endpoint), false, removedData->isClient);
1548 OICFree(removedData->data);
1549 removedData->data = NULL;
1551 OICFree(removedData->tlsdata);
1552 removedData->tlsdata = NULL;
1554 OICFree(removedData);
1557 OIC_LOG(DEBUG, TAG, "data is removed from session list");
1559 #ifndef DISABLE_TCP_SERVER
1560 if (caglobals.server && MAX_CONNECTION_COUNTS == u_arraylist_length(caglobals.tcp.svrlist) + 1)
1562 CATCPInitializeSocket();
1566 return CA_STATUS_OK;
1569 void CATCPDisconnectAll()
1571 OIC_LOG(DEBUG, TAG, "IN - CATCPDisconnectAll");
1573 oc_mutex_lock(g_mutexObjectList);
1575 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1576 for (ssize_t index = length; index > 0; index--)
1578 // disconnect session from remote device.
1579 CADisconnectTCPSession(index - 1);
1582 u_arraylist_destroy(caglobals.tcp.svrlist);
1583 caglobals.tcp.svrlist = NULL;
1585 oc_mutex_unlock(g_mutexObjectList);
1588 CAcloseSslConnectionAll(CA_ADAPTER_TCP);
1591 OIC_LOG(DEBUG, TAG, "OUT - CATCPDisconnectAll");
1594 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
1596 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1597 VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
1599 OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1601 // get connection info from list
1602 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1603 for (size_t i = 0; i < length; i++)
1605 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1606 caglobals.tcp.svrlist, i);
1612 if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1613 sizeof(svritem->sep.endpoint.addr))
1614 && (svritem->sep.endpoint.port == endpoint->port)
1615 && (svritem->sep.endpoint.flags & endpoint->flags))
1617 OIC_LOG(DEBUG, TAG, "Found in session list");
1623 OIC_LOG(DEBUG, TAG, "Session not found");
1627 CASocketFd_t CAGetSocketFDFromEndpoint(const CAEndpoint_t *endpoint)
1629 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1631 OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1633 // get connection info from list.
1634 oc_mutex_lock(g_mutexObjectList);
1635 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1636 for (size_t i = 0; i < length; i++)
1638 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1639 caglobals.tcp.svrlist, i);
1645 if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1646 sizeof(svritem->sep.endpoint.addr))
1647 && (svritem->sep.endpoint.port == endpoint->port)
1648 && (svritem->sep.endpoint.flags & endpoint->flags))
1650 oc_mutex_unlock(g_mutexObjectList);
1651 OIC_LOG(DEBUG, TAG, "Found in session list");
1656 oc_mutex_unlock(g_mutexObjectList);
1657 OIC_LOG(DEBUG, TAG, "Session not found");
1658 return OC_INVALID_SOCKET;
1661 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1664 // check from the last item.
1665 CATCPSessionInfo_t *svritem = NULL;
1666 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1667 for (size_t i = 0; i < length; i++)
1669 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1671 if (svritem && svritem->fd == fd)
1674 oc_mutex_unlock(g_mutexObjectList);
1683 static CATCPSessionInfo_t *CAGetSessionInfoFromFDAsOwner(int fd, size_t *index)
1685 CATCPSessionInfo_t *svritem = NULL;
1686 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1687 for (size_t i = 0; i < length; i++)
1689 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1691 if (svritem && svritem->fd == fd)
1701 CAResult_t CASearchAndDeleteTCPSession(const CAEndpoint_t *endpoint)
1703 oc_mutex_lock(g_mutexObjectList);
1705 CAResult_t result = CA_STATUS_OK;
1707 CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1710 result = CADisconnectTCPSession(index);
1711 if (CA_STATUS_OK != result)
1713 OIC_LOG_V(ERROR, TAG, "CADisconnectTCPSession failed, result[%d]", result);
1717 oc_mutex_unlock(g_mutexObjectList);
1721 void CATCPCloseInProgressConnections()
1723 OIC_LOG(INFO, TAG, "IN - CATCPCloseInProgressConnections");
1725 oc_mutex_lock(g_mutexObjectList);
1727 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1728 for (size_t index = 0; index < length; index++)
1730 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1731 caglobals.tcp.svrlist, index);
1737 // Session which are connecting state
1738 if (svritem->fd >= 0 && svritem->state == CONNECTING)
1740 shutdown(svritem->fd, SHUT_RDWR);
1743 svritem->state = DISCONNECTED;
1747 oc_mutex_unlock(g_mutexObjectList);
1749 OIC_LOG(INFO, TAG, "OUT - CATCPCloseInProgressConnections");
1752 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1754 OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1756 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1757 ((unsigned char *)recvBuffer)[0] >> 4);
1758 size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1760 size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1762 OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%zu]", optPaylaodLen);
1763 OIC_LOG_V(DEBUG, TAG, "header length [%zu]", headerLen);
1764 OIC_LOG_V(DEBUG, TAG, "total data length [%zu]", headerLen + optPaylaodLen);
1766 OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1767 return headerLen + optPaylaodLen;
1770 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1772 g_tcpErrorHandler = errorHandleCallback;