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"
52 #include "catcpserver_mutex.h"
54 #include "oic_malloc.h"
55 #include "oic_string.h"
58 #include "ca_adapter_net_ssl.h"
62 * Logging tag for module name.
64 //#define TAG "OIC_CA_TCP_SERVER"
65 #define TAG TCP_SERVER_TAG
68 * Maximum CoAP over TCP header length
69 * to know the total data length.
71 #define COAP_MAX_HEADER_SIZE 6
76 #define TLS_HEADER_SIZE 5
79 * Max Connection Counts.
81 #define MAX_CONNECTION_COUNTS 500
83 #define COAP_TCP_MAX_BUFFER_CHUNK_SIZE 65530 //64kb - 6 (coap+tcp max header size)
85 #define MILLISECONDS_PER_SECOND (1000)
90 static ca_thread_pool_t g_threadPool = NULL;
95 static uint32_t g_taskId = 0;
98 * Maintains the callback to be notified when data received from remote device.
100 static CATCPPacketReceivedCallback g_packetReceivedCallback = NULL;
103 * Error callback to update error in TCP.
105 static CATCPErrorHandleCallback g_tcpErrorHandler = NULL;
108 * Connected Callback to pass the connection information to RI.
110 static CATCPConnectionHandleCallback g_connectionCallback = NULL;
113 * Error code to hold the errno(Timeout, Destination unreachable, etc) when send/recv fails.
114 * Main purpose is to hold the reason for connection drop when keep-alive is in use.
115 * To indicate normal disconnection, 0 will be assigned.
117 static int g_lastErrorCode;
119 static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock);
120 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock);
121 static void CAFindReadyMessage();
122 static void CAPollReturned(struct pollfd *readFds, size_t size);
123 static void CAReceiveMessage(int fd);
124 static void CAReceiveHandler(void *data);
125 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem);
126 static void CATCPInitializeSocket();
127 static CATCPSessionInfo_t *CAGetSessionInfoFromFDAsOwner(int fd, size_t *index);
129 #if defined(__TIZEN__)
130 static char g_cloudproxyUri[CA_MAX_URI_LENGTH];
132 static char g_interfaceName[CA_MAX_INTERFACE_NAME_LEN];
134 CAResult_t CASetCloudAddressForProxy(const char *uri)
137 memset(g_cloudproxyUri, '\0', sizeof (g_cloudproxyUri));
139 OICStrcpy(g_cloudproxyUri, sizeof (g_cloudproxyUri), uri);
143 const char *CAGetCloudAddressForProxy()
145 if (g_cloudproxyUri[0] == '\0')
147 return g_cloudproxyUri;
150 CAResult_t CASetTCPServerSocketBindIP(const char* ifname)
152 CAResult_t res = CA_STATUS_OK;
154 VERIFY_NON_NULL_RET(ifname, TAG, "Interface name is NULL", CA_STATUS_INVALID_PARAM);
156 OIC_LOG(DEBUG, TAG, "Setting Socket Bind");
157 caglobals.tcp.bindenabled = true;
158 OICStrcpy(g_interfaceName, sizeof (g_interfaceName), ifname);
160 OIC_LOG(DEBUG, TAG, "Not supported!");
161 res = CA_NOT_SUPPORTED;
167 #define MAX_TCP_SOCK_COUNT 4
169 #define CLOSE_SOCKET(TYPE) \
170 if (caglobals.tcp.TYPE.fd != OC_INVALID_SOCKET) \
172 close(caglobals.tcp.TYPE.fd); \
173 caglobals.tcp.TYPE.fd = OC_INVALID_SOCKET; \
176 #define CA_FD_SET(TYPE, FDS, COUNT) \
177 FDS[COUNT].fd = caglobals.tcp.TYPE.fd; \
178 FDS[COUNT].events = POLLIN;
180 static void CAReceiveHandler(void *data)
183 OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler");
187 oc_mutex_lock(g_mutexObjectList);
188 if (caglobals.tcp.terminate)
190 oc_mutex_unlock(g_mutexObjectList);
193 oc_mutex_unlock(g_mutexObjectList);
194 CAFindReadyMessage();
197 oc_mutex_lock(g_mutexObjectList);
198 oc_cond_signal(g_condObjectList);
199 oc_mutex_unlock(g_mutexObjectList);
201 OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
204 static void CAFindReadyMessage()
206 int timeout = (caglobals.tcp.selectTimeout * 1000);
209 oc_mutex_lock(g_mutexObjectList);
210 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
212 // Consider 4 tcp sockets(ipv4, ipv4s, ipv6, ipv6s) + 1 connection fd + all sockets in svrlist
213 struct pollfd *readFds = (struct pollfd *)OICCalloc(MAX_TCP_SOCK_COUNT + 1 + length, sizeof(struct pollfd));
216 OIC_LOG_V(ERROR, TAG, "Failed to allocate memory!");
217 oc_mutex_unlock(g_mutexObjectList);
222 CA_FD_SET(ipv4, readFds, counter);
224 CA_FD_SET(ipv4s, readFds, counter);
226 CA_FD_SET(ipv6, readFds, counter);
228 CA_FD_SET(ipv6s, readFds, counter);
232 readFds[counter].fd = caglobals.tcp.connectionFds[0];
233 readFds[counter].events = POLLIN;
236 // All sockets in svrlist
237 for (size_t i = 0; i < length; i++)
239 CATCPSessionInfo_t *svritem =
240 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
241 if (svritem && 0 <= svritem->fd && CONNECTED == svritem->state)
243 readFds[counter].fd = svritem->fd;
244 readFds[counter].events = POLLIN;
248 oc_mutex_unlock(g_mutexObjectList);
249 int ret = poll(readFds, counter, timeout);
251 oc_mutex_lock(g_mutexObjectList);
252 if (caglobals.tcp.terminate)
254 OIC_LOG_V(INFO, TAG, "Packet receiver Stop request received.");
255 oc_mutex_unlock(g_mutexObjectList);
259 oc_mutex_unlock(g_mutexObjectList);
263 CAPollReturned(readFds, counter);
267 usleep(1000); /* some of the fields are not set by kernel on repeatedly calling
268 poll.Applying a sleep will solve this by providing a delay between
269 each subsequent poll system call */
273 OIC_LOG_V(FATAL, TAG, "poll error %s", strerror(errno));
279 static void CAPollReturned(struct pollfd *readFds, size_t size)
281 VERIFY_NON_NULL_VOID(readFds, TAG, "readFds is NULL");
283 if (caglobals.tcp.ipv4.fd != -1 && readFds[0].revents == POLLIN)
285 CAAcceptConnection(CA_IPV4, &caglobals.tcp.ipv4);
288 else if (caglobals.tcp.ipv4s.fd != -1 && readFds[1].revents == POLLIN)
290 CAAcceptConnection(CA_IPV4 | CA_SECURE, &caglobals.tcp.ipv4s);
293 else if (caglobals.tcp.ipv6.fd != -1 && readFds[2].revents == POLLIN)
295 CAAcceptConnection(CA_IPV6, &caglobals.tcp.ipv6);
298 else if (caglobals.tcp.ipv6s.fd != -1 && readFds[3].revents == POLLIN)
300 CAAcceptConnection(CA_IPV6 | CA_SECURE, &caglobals.tcp.ipv6s);
303 else if (-1 != caglobals.tcp.connectionFds[0] && readFds[4].revents != 0)
305 // new connection was created from remote device.
306 // exit the function to update read file descriptor.
307 char buf[MAX_ADDR_STR_SIZE_CA] = {0};
308 ssize_t len = read(caglobals.tcp.connectionFds[0], buf, sizeof (buf));
313 OIC_LOG_V(DEBUG, TAG, "Received new connection event with [%s]", buf);
318 int *readFDList = NULL;
319 size_t readFDListSize = 0;
321 oc_mutex_lock(g_mutexObjectList);
322 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
324 readFDList = (int*) OICCalloc(length, sizeof(int));
325 if (NULL == readFDList)
327 OIC_LOG_V(ERROR, TAG, "Failed to allocate memory!");
328 oc_mutex_unlock(g_mutexObjectList);
332 for (size_t i = 0; i < length; i++)
334 CATCPSessionInfo_t *svritem =
335 (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
336 if (svritem && svritem->fd >= 0)
341 if (svritem->fd == readFds[j].fd)
348 if (j < size && readFds[j].revents != 0)
350 readFDList[readFDListSize++] = svritem->fd;
354 oc_mutex_unlock(g_mutexObjectList);
356 // Read incomming messages from fds
357 for (size_t i = 0; i < readFDListSize; i++)
359 CAReceiveMessage(readFDList[i]);
366 static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock)
368 OIC_LOG_V(INFO, TAG, "In %s", __func__);
369 VERIFY_NON_NULL_VOID(sock, TAG, "sock is NULL");
371 if (MAX_CONNECTION_COUNTS == u_arraylist_length(caglobals.tcp.svrlist))
373 OIC_LOG_V(INFO, TAG, "Exceeding the max connection counts limit, close listening port");
375 sock->fd = OC_INVALID_SOCKET;
379 struct sockaddr_storage clientaddr;
380 socklen_t clientlen = sizeof (struct sockaddr_in);
383 clientlen = sizeof(struct sockaddr_in6);
386 CASocketFd_t sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen);
387 if (OC_INVALID_SOCKET != sockfd)
389 CATCPSessionInfo_t *svritem =
390 (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
393 OIC_LOG(ERROR, TAG, "Out of memory");
398 svritem->fd = sockfd;
399 svritem->sep.endpoint.flags = flag;
400 svritem->sep.endpoint.adapter = CA_ADAPTER_TCP;
401 svritem->state = CONNECTED;
402 svritem->isClient = false;
403 CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
404 svritem->sep.endpoint.addr, &svritem->sep.endpoint.port);
406 // Allocate message buffer
407 svritem->tlsdata = (unsigned char*) OICCalloc(TLS_DATA_MAX_SIZE, sizeof(unsigned char));
408 if (!svritem->tlsdata)
410 OIC_LOG(ERROR, TAG, "Out of memory");
416 oc_mutex_lock(g_mutexObjectList);
417 bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem);
420 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
422 OICFree(svritem->tlsdata);
424 oc_mutex_unlock(g_mutexObjectList);
427 oc_mutex_unlock(g_mutexObjectList);
429 // pass the connection information to CA Common Layer.
430 if (g_connectionCallback)
432 g_connectionCallback(&(svritem->sep.endpoint), true, svritem->isClient);
435 OIC_LOG_V(INFO, TAG, "Out %s", __func__);
439 * Clean socket state data
441 * @param[in/out] item - socket state data
443 void CACleanData(CATCPSessionInfo_t *svritem)
447 OICFree(svritem->data);
448 svritem->data = NULL;
453 svritem->totalLen = 0;
455 svritem->protocol = UNKNOWN;
460 * Construct CoAP header and payload from buffer
462 * @param[in] svritem - used socket, buffer, current received message length and protocol
463 * @param[in/out] data - data buffer, this value is updated as data is copied to svritem
464 * @param[in/out] dataLength - length of data, this value decreased as data is copied to svritem
465 * @return - CA_STATUS_OK or appropriate error code
467 CAResult_t CAConstructCoAP(CATCPSessionInfo_t *svritem, unsigned char **data,
470 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
472 if (NULL == svritem || NULL == data || NULL == dataLength)
474 OIC_LOG(ERROR, TAG, "Invalid input parameter(NULL)");
475 return CA_STATUS_INVALID_PARAM;
478 unsigned char *inBuffer = *data;
479 size_t inLen = *dataLength;
480 OIC_LOG_V(DEBUG, TAG, "before-datalength : %zd", *dataLength);
482 if (NULL == svritem->data && inLen > 0)
484 // allocate memory for message header (CoAP header size because it is bigger)
485 svritem->data = (unsigned char *) OICCalloc(1, COAP_MAX_HEADER_SIZE);
486 if (NULL == svritem->data)
488 OIC_LOG(ERROR, TAG, "OICCalloc - out of memory");
489 return CA_MEMORY_ALLOC_FAILED;
492 // copy 1 byte to parse coap header length
493 memcpy(svritem->data, inBuffer, 1);
495 svritem->bufLen = COAP_MAX_HEADER_SIZE;
500 //if not enough data received - read them on next CAFillHeader() call
506 //if enough data received - parse header
507 svritem->protocol = COAP;
509 //seems CoAP data received. read full coap header.
510 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(svritem->data[0] >> 4);
511 size_t headerLen = coap_get_tcp_header_length_for_transport(transport);
515 if (svritem->len < headerLen)
517 copyLen = headerLen - svritem->len;
523 //read required bytes to have full CoAP header
524 memcpy(svritem->data + svritem->len, inBuffer, copyLen);
525 svritem->len += copyLen;
529 //if not enough data received - read them on next CAFillHeader() call
530 if (svritem->len < headerLen)
534 OIC_LOG(DEBUG, TAG, "CoAP header received partially. Wait for rest header data");
538 //calculate CoAP message length
539 svritem->totalLen = CAGetTotalLengthFromHeader(svritem->data);
545 // Calculate length of data to be copied.
546 copyLen = svritem->totalLen - svritem->len;
552 // Is buffer not big enough for remaining data ?
553 if (svritem->len + copyLen > svritem->bufLen)
555 // Resize buffer to accommodate enough space
556 size_t extLen = svritem->totalLen - svritem->bufLen;
557 if (extLen > COAP_TCP_MAX_BUFFER_CHUNK_SIZE)
559 extLen = COAP_TCP_MAX_BUFFER_CHUNK_SIZE;
562 // Allocate required memory
563 unsigned char *buffer = OICRealloc(svritem->data, svritem->bufLen + extLen);
566 OIC_LOG(ERROR, TAG, "OICRealloc - out of memory");
567 return CA_MEMORY_ALLOC_FAILED;
570 svritem->data = buffer;
571 svritem->bufLen += extLen;
574 // Read required bytes to have full CoAP payload
575 memcpy(svritem->data + svritem->len, inBuffer, copyLen);
576 svritem->len += copyLen;
584 OIC_LOG_V(DEBUG, TAG, "after-datalength : %zd", *dataLength);
585 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
589 static void CAReceiveMessage(int fd)
591 CAResult_t res = CA_STATUS_OK;
593 oc_mutex_lock(g_mutexObjectList);
595 //get remote device information from file descriptor.
597 CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFDAsOwner(fd, &index);
600 OIC_LOG(ERROR, TAG, "there is no connection information in list");
601 oc_mutex_unlock(g_mutexObjectList);
605 CASecureEndpoint_t peerEP = svritem->sep;
607 if (svritem->sep.endpoint.flags & CA_SECURE) // Secure connection
609 svritem->protocol = TLS;
613 size_t tlsLength = 0;
615 if (TLS_HEADER_SIZE > svritem->tlsLen)
617 nbRead = TLS_HEADER_SIZE - svritem->tlsLen;
621 //[3][4] bytes in tls header are tls payload length
622 tlsLength = TLS_HEADER_SIZE +
623 (size_t)((svritem->tlsdata[3] << 8) | svritem->tlsdata[4]);
624 OIC_LOG_V(DEBUG, TAG, "total tls length = %zd", tlsLength);
625 if (tlsLength > TLS_DATA_MAX_SIZE)
627 OIC_LOG_V(ERROR, TAG, "total tls length is too big (buffer size : %u)",
629 oc_mutex_unlock(g_mutexObjectList);
630 CATCPDisconnectSession(&peerEP.endpoint);
633 nbRead = tlsLength - svritem->tlsLen;
636 len = recv(fd, svritem->tlsdata + svritem->tlsLen, nbRead, 0);
639 g_lastErrorCode = errno;
640 OIC_LOG_V(DEBUG, TAG, "Set g_lastErrorCode to %s", strerror(g_lastErrorCode));
641 OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(g_lastErrorCode));
642 res = CA_RECEIVE_FAILED;
647 OIC_LOG(DEBUG, TAG, "Set g_lastErrorCode to 0");
648 OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
649 svritem->state = DISCONNECTED;
650 res = CA_DESTINATION_DISCONNECTED;
654 svritem->tlsLen += len;
655 OIC_LOG_V(DEBUG, TAG, "nb_read : %zd bytes , recv() : %d bytes, svritem->tlsLen : %zd bytes",
656 nbRead, len, svritem->tlsLen);
657 if (tlsLength > 0 && tlsLength == svritem->tlsLen)
659 // When successfully read data - pass them to callback.
660 // Dont invoke callback locking mutex
661 unsigned char *mesBuf = svritem->tlsdata;
662 size_t mesBufLen = svritem->tlsLen;
663 svritem->tlsdata = NULL;
664 oc_mutex_unlock(g_mutexObjectList);
666 res = CAdecryptSsl(&peerEP, (uint8_t *)mesBuf, mesBufLen);
667 OIC_LOG_V(INFO, TAG, "%s: CAdecryptSsl returned %d", __func__, res);
669 // Check for the svritem and reset buffer
670 oc_mutex_lock(g_mutexObjectList);
671 svritem = CAGetSessionInfoFromFDAsOwner(fd, &index);
674 svritem->tlsdata = mesBuf;
679 // svritem does not exist, thus free the message buffer
680 OIC_LOG(ERROR, TAG, "svritem not found. Freeing message buffer!");
687 else // Non-Secure connection
689 svritem->protocol = COAP;
691 // svritem->tlsdata can also be used as receiving buffer in case of raw tcp
692 len = recv(fd, svritem->tlsdata, TLS_DATA_MAX_SIZE, 0);
695 g_lastErrorCode = errno;
696 OIC_LOG_V(DEBUG, TAG, "Set g_lastErrorCode to %s", strerror(g_lastErrorCode));
697 OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(g_lastErrorCode));
698 res = CA_RECEIVE_FAILED;
703 OIC_LOG_V(DEBUG, TAG, "Set g_lastErrorCode to 0");
704 OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection");
705 res = CA_DESTINATION_DISCONNECTED;
709 //when successfully read data - pass them to callback.
710 OIC_LOG_V(DEBUG, TAG, "recv() : %d bytes", len);
711 if (g_packetReceivedCallback)
713 // Dont invoke callback locking mutex
714 unsigned char *mesBuf = svritem->tlsdata;
715 svritem->tlsdata = NULL;
716 oc_mutex_unlock(g_mutexObjectList);
718 res = g_packetReceivedCallback(&peerEP, mesBuf, len);
720 // Check for the svritem and reset buffer
721 oc_mutex_lock(g_mutexObjectList);
722 svritem = CAGetSessionInfoFromFDAsOwner(fd, &index);
725 svritem->tlsdata = mesBuf;
730 // svritem does not exist, thus free the message buffer
731 OIC_LOG(ERROR, TAG, "svritem not found. Freeing message buffer!");
738 oc_mutex_unlock(g_mutexObjectList);
740 if (res != CA_STATUS_OK)
742 CATCPDisconnectSession(&peerEP.endpoint);
746 static ssize_t CAWakeUpForReadFdsUpdate(const char *host)
748 if (caglobals.tcp.connectionFds[1] != -1)
753 len = write(caglobals.tcp.connectionFds[1], host, strlen(host));
754 } while ((len == -1) && (errno == EINTR));
756 if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
758 OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
765 static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port,
766 struct sockaddr_storage *sockaddr)
768 struct addrinfo *addrs = NULL;
769 struct addrinfo hints = { .ai_family = family,
770 .ai_protocol = IPPROTO_TCP,
771 .ai_socktype = SOCK_STREAM,
772 .ai_flags = AI_NUMERICHOST };
774 int r = getaddrinfo(host, NULL, &hints, &addrs);
779 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: errno %s", strerror(errno));
783 OIC_LOG_V(ERROR, TAG, "getaddrinfo failed: %s", gai_strerror(r));
786 return CA_STATUS_FAILED;
788 // assumption: in this case, getaddrinfo will only return one addrinfo
789 // or first is the one we want.
790 if (addrs[0].ai_family == AF_INET6)
792 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in6));
793 ((struct sockaddr_in6 *)sockaddr)->sin6_port = htons(port);
797 memcpy(sockaddr, addrs[0].ai_addr, sizeof (struct sockaddr_in));
798 ((struct sockaddr_in *)sockaddr)->sin_port = htons(port);
804 #if defined(__TIZEN__)
805 static char * CATCPGetInterfaceAddr()
807 struct ifaddrs *ifaddr, *ifa;
809 char *host = (uint8_t *)OICMalloc(NI_MAXHOST);
811 if (getifaddrs(&ifaddr) == -1)
813 OIC_LOG_V(ERROR, TAG, "getifaddrs failed: errno %s", strerror(errno));
818 for (ifa = ifaddr, n = 0; ifa != NULL; ifa = ifa->ifa_next, n++)
820 if (ifa->ifa_addr == NULL)
823 family = ifa->ifa_addr->sa_family;
824 OIC_LOG_V(DEBUG, TAG,"Interface name: %s",ifa->ifa_name);
826 if ((strncmp(g_interfaceName,ifa->ifa_name,strlen(ifa->ifa_name))==0)
827 && (family == AF_INET || family == AF_INET6))
829 s = getnameinfo(ifa->ifa_addr, (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6),
830 host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
833 OIC_LOG_V(ERROR, TAG, "getnameinfo failed: errno %s", strerror(errno));
839 OIC_LOG_V(DEBUG, TAG, "Interface address: %s", host);
847 OIC_LOG(ERROR, TAG, "Interface address not found");
852 #if defined(__TIZEN__)
853 static int CAGetHTTPStatusCode(char * response) {
854 char *resp, *code_plus, *ptrSave;
857 resp = strdup(response);
858 strtok_r(resp, " ", &ptrSave); /* skip HTTP version */
859 code_plus = strtok_r(NULL, " ", &ptrSave);
861 ret = code_plus ? atoi(code_plus) : -1;
867 static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem)
869 VERIFY_NON_NULL(svritem, TAG, "svritem is NULL");
871 OIC_LOG_V(INFO, TAG, "try to connect with [%s:%u]",
872 svritem->sep.endpoint.addr, svritem->sep.endpoint.port);
874 // #1. create tcp socket.
875 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
878 OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
879 return CA_SOCKET_OPERATION_FAILED;
883 // #2. convert address from string to binary.
884 struct sockaddr_storage sa = { .ss_family = family };
885 CAResult_t res = CATCPConvertNameToAddr(family, svritem->sep.endpoint.addr,
886 svritem->sep.endpoint.port, &sa);
887 if (CA_STATUS_OK != res)
889 OIC_LOG(ERROR, TAG, "convert name to sockaddr failed");
890 return CA_SOCKET_OPERATION_FAILED;
893 // #3. set socket length.
894 socklen_t socklen = 0;
895 if (sa.ss_family == AF_INET6)
897 struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sa;
898 if (!sock6->sin6_scope_id)
900 sock6->sin6_scope_id = svritem->sep.endpoint.ifindex;
902 socklen = sizeof(struct sockaddr_in6);
906 socklen = sizeof(struct sockaddr_in);
909 #if defined(__TIZEN__)
910 if (caglobals.tcp.bindenabled)
912 char *host_address = CATCPGetInterfaceAddr();
915 if (sa.ss_family == AF_INET)
917 struct sockaddr_in client;
918 memset(&client, 0x00, sizeof(client));
919 client.sin_family = AF_INET;
920 inet_pton(AF_INET, host_address, &(client.sin_addr.s_addr));
921 if (-1 == bind(fd, (struct sockaddr *)&client, socklen))
923 OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
924 OICFree(host_address);
925 return CA_SOCKET_OPERATION_FAILED;
930 struct sockaddr_in6 client6;
931 memset(&client6, 0x00, sizeof(client6));
932 client6.sin6_family = AF_INET6;
933 inet_pton(AF_INET6, host_address, &client6.sin6_addr.s6_addr);
934 if (-1 == bind(fd, (struct sockaddr *)&client6, socklen))
936 OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
937 OICFree(host_address);
938 return CA_SOCKET_OPERATION_FAILED;
941 OICFree(host_address);
946 // #4. connect to remote server device.
947 if (connect(fd, (struct sockaddr *)&sa, socklen) < 0)
949 OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno));
950 CALogSendStateInfo(svritem->sep.endpoint.adapter, svritem->sep.endpoint.addr,
951 svritem->sep.endpoint.port, 0, false, strerror(errno));
952 return CA_SOCKET_OPERATION_FAILED;
955 OIC_LOG(INFO, TAG, "connect socket success");
956 svritem->state = CONNECTED;
957 ssize_t len = CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr);
960 OIC_LOG(ERROR, TAG, "wakeup receive thread failed");
961 return CA_SOCKET_OPERATION_FAILED;
964 #if defined(__TIZEN__)
965 // #5. Send HTTP CONNECT to proxy if proxy
967 const char *cloud_address = CAGetCloudAddressForProxy();
968 OIC_LOG_V(INFO, TAG, "Proxy : '%s'", cloud_address ? cloud_address : "(nil)");
970 if(cloud_address && *cloud_address)
973 int len = snprintf(message, 4096,
974 "CONNECT %s HTTP/1.1\r\n"
975 "Host: %s\r\n\r\n", cloud_address, cloud_address
978 ssize_t l = send(fd, message, len, 0);
981 OIC_LOG_V(ERROR, TAG, "failed to send HTTP CONNECT data (expected %d bytes, ret %zd)", len, l);
984 return CA_SOCKET_OPERATION_FAILED;
987 // maybe this should be called in other thread, it causes bottleneck.
988 OIC_LOG_V(INFO, TAG, "Message sent is : '%s'\n", message);
991 OIC_LOG_V(INFO, TAG, "Receiving response to CONNECT from proxy...");
993 l = recv(fd, message, 4096, 0);
995 OIC_LOG_V(INFO, TAG, "Received data : '%s'", message);
996 OIC_LOG_V(INFO, TAG, "Received len = %zd", l);
998 int status_code = CAGetHTTPStatusCode(message);
1000 OIC_LOG_V(INFO, TAG, "HTTP status_code : %d", status_code);
1001 if(status_code < 200 || status_code > 299)
1003 OIC_LOG_V(ERROR, TAG, "Error, Wrong status code: %d", status_code);
1006 return CA_SOCKET_OPERATION_FAILED;
1011 return CA_STATUS_OK;
1014 static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock)
1016 VERIFY_NON_NULL_RET(sock, TAG, "sock", -1);
1018 if (OC_INVALID_SOCKET != sock->fd)
1020 OIC_LOG(DEBUG, TAG, "accept socket created already");
1024 socklen_t socklen = 0;
1025 struct sockaddr_storage server = { .ss_family = family };
1027 int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
1028 if (OC_INVALID_SOCKET == fd)
1030 OIC_LOG(ERROR, TAG, "Failed to create socket");
1034 if (family == AF_INET6)
1036 // the socket is restricted to sending and receiving IPv6 packets only.
1038 //TODO: enable once IPv6 is supported
1040 if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
1042 OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
1046 ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port);
1047 socklen = sizeof (struct sockaddr_in6);
1051 ((struct sockaddr_in *)&server)->sin_port = htons(sock->port);
1052 socklen = sizeof (struct sockaddr_in);
1056 if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)))
1058 OIC_LOG(ERROR, TAG, "setsockopt SO_REUSEADDR");
1062 if (-1 == bind(fd, (struct sockaddr *)&server, socklen))
1064 OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
1068 if (listen(fd, caglobals.tcp.listenBacklog) != 0)
1070 OIC_LOG(ERROR, TAG, "listen() error");
1074 if (sock->port) // use the given port
1077 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof (on)))
1079 OIC_LOG_V(ERROR, TAG, "SO_REUSEADDR failed: %s", strerror(errno));
1081 return OC_INVALID_SOCKET;
1084 else // return the assigned port
1086 if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen))
1088 OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
1091 sock->port = ntohs(family == AF_INET6 ?
1092 ((struct sockaddr_in6 *)&server)->sin6_port :
1093 ((struct sockaddr_in *)&server)->sin_port);
1103 return OC_INVALID_SOCKET;
1106 static void CAInitializePipe(int *fds)
1108 int ret = pipe(fds);
1109 // TODO: Remove temporary workaround once F_GETFD / F_SETFD support is in TizenRT
1110 /* Temporary workaround: By pass F_GETFD / F_SETFD */
1120 OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
1125 ret = fcntl(fds[0], F_GETFD);
1128 ret = fcntl(fds[0], F_SETFD, ret|FD_CLOEXEC);
1132 ret = fcntl(fds[1], F_GETFD);
1136 ret = fcntl(fds[1], F_SETFD, ret|FD_CLOEXEC);
1146 OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
1152 #ifndef DISABLE_TCP_SERVER
1153 #define NEWSOCKET(FAMILY, NAME) \
1154 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
1155 if (caglobals.tcp.NAME.fd == -1) \
1157 caglobals.tcp.NAME.port = 0; \
1158 caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \
1161 void CATCPInitializeSocket()
1163 #ifndef __WITH_TLS__
1164 NEWSOCKET(AF_INET, ipv4);
1166 NEWSOCKET(AF_INET, ipv4s);
1169 //TODO Enable once TizenRT supports IPv6
1171 #ifndef __WITH_TLS__
1172 NEWSOCKET(AF_INET6, ipv6);
1174 NEWSOCKET(AF_INET6, ipv6s);
1177 #ifndef __WITH_TLS__
1178 OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d",
1179 caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port);
1180 OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d",
1181 caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port);
1183 OIC_LOG_V(DEBUG, TAG, "IPv4 secure socket fd=%d, port=%d",
1184 caglobals.tcp.ipv4s.fd, caglobals.tcp.ipv4s.port);
1185 OIC_LOG_V(DEBUG, TAG, "IPv6 secure socket fd=%d, port=%d",
1186 caglobals.tcp.ipv6s.fd, caglobals.tcp.ipv6s.port);
1189 #endif // DISABLE_TCP_SERVER
1191 CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool)
1193 oc_mutex_lock(g_mutexObjectList);
1194 if (caglobals.tcp.started)
1196 oc_mutex_unlock(g_mutexObjectList);
1197 OIC_LOG(INFO, TAG, "Adapter is started already");
1198 return CA_STATUS_OK;
1201 g_threadPool = threadPool;
1203 if (!caglobals.tcp.ipv4tcpenabled)
1205 caglobals.tcp.ipv4tcpenabled = true; // only needed to run CA tests
1207 if (!caglobals.tcp.ipv6tcpenabled)
1209 caglobals.tcp.ipv6tcpenabled = true; // only needed to run CA tests
1212 caglobals.tcp.terminate = false;
1213 if (!caglobals.tcp.svrlist)
1215 caglobals.tcp.svrlist = u_arraylist_create();
1218 #ifndef DISABLE_TCP_SERVER
1219 if (caglobals.server)
1221 CATCPInitializeSocket();
1226 // create pipe for fast shutdown
1227 CAInitializePipe(caglobals.tcp.shutdownFds);
1229 // create pipe for connection event
1230 CAInitializePipe(caglobals.tcp.connectionFds);
1232 CAResult_t res = CA_STATUS_OK;
1234 res = ca_thread_pool_add_task(g_threadPool, CAReceiveHandler, NULL, &g_taskId);
1236 res = ca_thread_pool_add_task(g_threadPool, CAReceiveHandler, NULL, NULL,
1237 "IoT_TCPReceive", CONFIG_IOTIVITY_TCPRECEIVE_PTHREAD_STACKSIZE);
1239 if (CA_STATUS_OK != res)
1241 oc_mutex_unlock(g_mutexObjectList);
1242 OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
1247 caglobals.tcp.started = true;
1248 oc_mutex_unlock(g_mutexObjectList);
1250 OIC_LOG(INFO, TAG, "CAReceiveHandler thread started successfully.");
1251 return CA_STATUS_OK;
1254 void CATCPStopServer()
1256 oc_mutex_lock(g_mutexObjectList);
1257 if (caglobals.tcp.terminate)
1259 oc_mutex_unlock(g_mutexObjectList);
1260 OIC_LOG(INFO, TAG, "Adapter is not enabled");
1264 // set terminate flag.
1265 caglobals.tcp.terminate = true;
1267 oc_mutex_lock(g_mutexSend);
1268 oc_cond_signal(g_condSend);
1269 oc_mutex_unlock(g_mutexSend);
1272 if (caglobals.tcp.started)
1274 oc_cond_wait(g_condObjectList, g_mutexObjectList);
1275 caglobals.tcp.started = false;
1279 // close accept socket.
1280 #ifndef __WITH_TLS__
1284 CLOSE_SOCKET(ipv4s);
1285 CLOSE_SOCKET(ipv6s);
1288 if (caglobals.tcp.connectionFds[1] != OC_INVALID_SOCKET)
1290 close(caglobals.tcp.connectionFds[1]);
1291 caglobals.tcp.connectionFds[1] = OC_INVALID_SOCKET;
1293 if (caglobals.tcp.connectionFds[0] != OC_INVALID_SOCKET)
1295 close(caglobals.tcp.connectionFds[0]);
1296 caglobals.tcp.connectionFds[0] = OC_INVALID_SOCKET;
1299 if (caglobals.tcp.shutdownFds[1] != OC_INVALID_SOCKET)
1301 close(caglobals.tcp.shutdownFds[1]);
1302 caglobals.tcp.shutdownFds[1] = OC_INVALID_SOCKET;
1303 // receive thread will stop immediately
1305 if (caglobals.tcp.started)
1307 oc_cond_wait(g_condObjectList, g_mutexObjectList);
1308 caglobals.tcp.started = false;
1310 if (caglobals.tcp.shutdownFds[0] != OC_INVALID_SOCKET)
1312 close(caglobals.tcp.shutdownFds[0]);
1313 caglobals.tcp.shutdownFds[0] = OC_INVALID_SOCKET;
1316 oc_mutex_unlock(g_mutexObjectList);
1319 ca_thread_pool_remove_task(g_threadPool, g_taskId);
1322 CATCPDisconnectAll();
1324 OIC_LOG(INFO, TAG, "Adapter terminated successfully");
1327 void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback)
1329 g_packetReceivedCallback = callback;
1332 void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler)
1334 g_connectionCallback = connHandler;
1337 size_t CACheckPayloadLengthFromHeader(const void *data, size_t dlen)
1339 VERIFY_NON_NULL_RET(data, TAG, "data", -1);
1341 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1342 ((unsigned char *)data)[0] >> 4);
1344 coap_pdu_t *pdu = coap_new_pdu2(transport, dlen);
1347 OIC_LOG(ERROR, TAG, "outpdu is null");
1348 OIC_LOG_V(ERROR, TAG, "data length: %zu", dlen);
1352 int ret = coap_pdu_parse2((unsigned char *) data, dlen, pdu, transport);
1355 OIC_LOG(ERROR, TAG, "pdu parse failed");
1356 coap_delete_pdu(pdu);
1360 size_t payloadLen = 0;
1361 size_t headerSize = coap_get_tcp_header_length_for_transport(transport);
1362 OIC_LOG_V(DEBUG, TAG, "headerSize : %zu, pdu length : %d",
1363 headerSize, pdu->length);
1364 if (pdu->length > headerSize)
1366 payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
1374 static ssize_t sendData(const CAEndpoint_t *endpoint, const void *data,
1375 size_t dlen, const char *fam)
1377 OIC_LOG_V(INFO, TAG, "The length of data that needs to be sent is %zu bytes", dlen);
1379 // #1. find a session info from list.
1380 CASocketFd_t sockFd = CAGetSocketFDFromEndpoint(endpoint);
1381 if (OC_INVALID_SOCKET == sockFd)
1383 // if there is no connection info, connect to remote device.
1384 sockFd = CAConnectTCPSession(endpoint);
1385 if (OC_INVALID_SOCKET == sockFd)
1387 OIC_LOG(ERROR, TAG, "Failed to create tcp session object");
1392 // #2. send data to remote device.
1393 ssize_t remainLen = dlen;
1394 unsigned int sendRetryTime = 1;
1398 ssize_t len = send(sockFd, data, remainLen, MSG_DONTWAIT | MSG_NOSIGNAL);
1400 ssize_t len = send(sockFd, data, remainLen, MSG_DONTWAIT);
1404 g_lastErrorCode = errno;
1405 OIC_LOG_V(DEBUG, TAG, "Set g_lastErrorCode to %s", strerror(g_lastErrorCode));
1406 if (EWOULDBLOCK != g_lastErrorCode && EAGAIN != g_lastErrorCode)
1408 OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(g_lastErrorCode));
1409 CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
1410 len, false, strerror(g_lastErrorCode));
1414 // re-trying send after 10, 20, 40, 80, 160 and 320 milliseconds
1415 if (sendRetryTime > 32)
1420 unsigned int waitTime = sendRetryTime * 10 * MILLISECONDS_PER_SECOND;
1421 OIC_LOG_V(WARNING, TAG, "send blocked. trying send after %u microseconds", waitTime);
1423 oc_mutex_lock(g_mutexSend);
1424 oc_cond_wait_for(g_condSend, g_mutexSend, waitTime);
1425 oc_mutex_unlock(g_mutexSend);
1427 oc_mutex_lock(g_mutexObjectList);
1428 if (caglobals.tcp.terminate)
1430 oc_mutex_unlock(g_mutexObjectList);
1433 oc_mutex_unlock(g_mutexObjectList);
1435 sendRetryTime = (sendRetryTime << 1);
1442 } while (remainLen > 0);
1447 OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen);
1448 CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
1453 ssize_t CATCPSendData(CAEndpoint_t *endpoint, const void *data, size_t datalen)
1455 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", -1);
1456 VERIFY_NON_NULL_RET(data, TAG, "data is NULL", -1);
1458 if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6))
1460 return sendData(endpoint, data, datalen, "ipv6");
1462 if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4))
1464 return sendData(endpoint, data, datalen, "ipv4");
1467 OIC_LOG(ERROR, TAG, "Not supported transport flags");
1471 CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1473 VERIFY_NON_NULL(info, TAG, "info is NULL");
1474 VERIFY_NON_NULL(size, TAG, "size is NULL");
1476 return CA_NOT_SUPPORTED;
1479 CASocketFd_t CAConnectTCPSession(const CAEndpoint_t *endpoint)
1481 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1483 // #1. create TCP server object
1484 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem));
1487 OIC_LOG(ERROR, TAG, "Out of memory");
1488 return OC_INVALID_SOCKET;
1490 memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr));
1491 svritem->sep.endpoint.adapter = endpoint->adapter;
1492 svritem->sep.endpoint.port = endpoint->port;
1493 svritem->sep.endpoint.flags = endpoint->flags;
1494 svritem->sep.endpoint.ifindex = endpoint->ifindex;
1495 svritem->state = CONNECTING;
1496 svritem->isClient = true;
1498 // Allocate message buffer
1499 svritem->tlsdata = (unsigned char*) OICCalloc(TLS_DATA_MAX_SIZE, sizeof(unsigned char));
1500 if (!svritem->tlsdata)
1502 OIC_LOG(ERROR, TAG, "Out of memory");
1504 return OC_INVALID_SOCKET;
1507 // #2. add TCP connection info to list
1508 oc_mutex_lock(g_mutexObjectList);
1509 if (caglobals.tcp.svrlist)
1511 bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem);
1514 OIC_LOG(ERROR, TAG, "u_arraylist_add failed.");
1516 OICFree(svritem->tlsdata);
1518 oc_mutex_unlock(g_mutexObjectList);
1519 return OC_INVALID_SOCKET;
1522 oc_mutex_unlock(g_mutexObjectList);
1524 // #3. create the socket and connect to TCP server
1525 int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET;
1526 if (CA_STATUS_OK != CATCPCreateSocket(family, svritem))
1528 return OC_INVALID_SOCKET;
1531 // #4. pass the connection information to CA Common Layer.
1532 if (g_connectionCallback)
1534 g_connectionCallback(&(svritem->sep.endpoint), true, svritem->isClient);
1540 CAResult_t CADisconnectTCPSession(size_t index)
1542 CATCPSessionInfo_t *removedData = u_arraylist_remove(caglobals.tcp.svrlist, index);
1545 OIC_LOG(DEBUG, TAG, "there is no data to be removed");
1546 return CA_STATUS_OK;
1549 // close the socket and remove session info in list.
1550 if (removedData->fd >= 0)
1552 shutdown(removedData->fd, SHUT_RDWR);
1553 close(removedData->fd);
1554 removedData->fd = -1;
1555 removedData->state = (CONNECTED == removedData->state) ?
1556 DISCONNECTED : removedData->state;
1558 // pass the connection information to CA Common Layer.
1559 if (g_connectionCallback && DISCONNECTED == removedData->state)
1561 g_connectionCallback(&(removedData->sep.endpoint), false, removedData->isClient);
1564 OICFree(removedData->data);
1565 removedData->data = NULL;
1567 OICFree(removedData->tlsdata);
1568 removedData->tlsdata = NULL;
1570 OICFree(removedData);
1573 OIC_LOG(DEBUG, TAG, "data is removed from session list");
1575 #ifndef DISABLE_TCP_SERVER
1576 if (caglobals.server && MAX_CONNECTION_COUNTS == u_arraylist_length(caglobals.tcp.svrlist) + 1)
1578 CATCPInitializeSocket();
1582 return CA_STATUS_OK;
1585 void CATCPDisconnectAll()
1587 OIC_LOG(DEBUG, TAG, "IN - CATCPDisconnectAll");
1589 oc_mutex_lock(g_mutexObjectList);
1591 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1592 for (ssize_t index = length; index > 0; index--)
1594 // disconnect session from remote device.
1595 CADisconnectTCPSession(index - 1);
1598 u_arraylist_destroy(caglobals.tcp.svrlist);
1599 caglobals.tcp.svrlist = NULL;
1601 oc_mutex_unlock(g_mutexObjectList);
1604 CAcloseSslConnectionAll(CA_ADAPTER_TCP);
1607 OIC_LOG(DEBUG, TAG, "OUT - CATCPDisconnectAll");
1610 CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index)
1612 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL);
1613 VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL);
1615 OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1617 // get connection info from list
1618 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1619 for (size_t i = 0; i < length; i++)
1621 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1622 caglobals.tcp.svrlist, i);
1628 if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1629 sizeof(svritem->sep.endpoint.addr))
1630 && (svritem->sep.endpoint.port == endpoint->port)
1631 && (svritem->sep.endpoint.flags & endpoint->flags))
1633 OIC_LOG(DEBUG, TAG, "Found in session list");
1639 OIC_LOG(DEBUG, TAG, "Session not found");
1643 CASocketFd_t CAGetSocketFDFromEndpoint(const CAEndpoint_t *endpoint)
1645 VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET);
1647 OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port);
1649 // get connection info from list.
1650 oc_mutex_lock(g_mutexObjectList);
1651 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1652 for (size_t i = 0; i < length; i++)
1654 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1655 caglobals.tcp.svrlist, i);
1661 if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr,
1662 sizeof(svritem->sep.endpoint.addr))
1663 && (svritem->sep.endpoint.port == endpoint->port)
1664 && (svritem->sep.endpoint.flags & endpoint->flags))
1666 oc_mutex_unlock(g_mutexObjectList);
1667 OIC_LOG(DEBUG, TAG, "Found in session list");
1672 oc_mutex_unlock(g_mutexObjectList);
1673 OIC_LOG(DEBUG, TAG, "Session not found");
1674 return OC_INVALID_SOCKET;
1677 CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index)
1680 // check from the last item.
1681 CATCPSessionInfo_t *svritem = NULL;
1682 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1683 for (size_t i = 0; i < length; i++)
1685 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1687 if (svritem && svritem->fd == fd)
1690 oc_mutex_unlock(g_mutexObjectList);
1699 static CATCPSessionInfo_t *CAGetSessionInfoFromFDAsOwner(int fd, size_t *index)
1701 CATCPSessionInfo_t *svritem = NULL;
1702 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1703 for (size_t i = 0; i < length; i++)
1705 svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i);
1707 if (svritem && svritem->fd == fd)
1717 CAResult_t CASearchAndDeleteTCPSession(const CAEndpoint_t *endpoint)
1719 oc_mutex_lock(g_mutexObjectList);
1721 CAResult_t result = CA_STATUS_OK;
1723 CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1726 result = CADisconnectTCPSession(index);
1727 if (CA_STATUS_OK != result)
1729 OIC_LOG_V(ERROR, TAG, "CADisconnectTCPSession failed, result[%d]", result);
1733 oc_mutex_unlock(g_mutexObjectList);
1737 void CATCPCloseInProgressConnections()
1739 OIC_LOG(INFO, TAG, "IN - CATCPCloseInProgressConnections");
1741 oc_mutex_lock(g_mutexObjectList);
1743 uint32_t length = u_arraylist_length(caglobals.tcp.svrlist);
1744 for (size_t index = 0; index < length; index++)
1746 CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(
1747 caglobals.tcp.svrlist, index);
1753 // Session which are connecting state
1754 if (svritem->fd >= 0 && svritem->state == CONNECTING)
1756 shutdown(svritem->fd, SHUT_RDWR);
1759 svritem->state = DISCONNECTED;
1763 oc_mutex_unlock(g_mutexObjectList);
1765 OIC_LOG(INFO, TAG, "OUT - CATCPCloseInProgressConnections");
1768 size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer)
1770 OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader");
1772 coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(
1773 ((unsigned char *)recvBuffer)[0] >> 4);
1774 size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer,
1776 size_t headerLen = coap_get_tcp_header_length((unsigned char *)recvBuffer);
1778 OIC_LOG_V(DEBUG, TAG, "option/paylaod length [%zu]", optPaylaodLen);
1779 OIC_LOG_V(DEBUG, TAG, "header length [%zu]", headerLen);
1780 OIC_LOG_V(DEBUG, TAG, "total data length [%zu]", headerLen + optPaylaodLen);
1782 OIC_LOG(DEBUG, TAG, "OUT - CAGetTotalLengthFromHeader");
1783 return headerLen + optPaylaodLen;
1786 void CATCPSetErrorHandler(CATCPErrorHandleCallback errorHandleCallback)
1788 g_tcpErrorHandler = errorHandleCallback;
1791 CAResult_t CASetKeepAlive(const CAEndpoint_t *endpoint, int time, int cnt, int intvl)
1793 OIC_LOG(INFO, TAG, "IN - CATCPSetKeepAlive");
1795 VERIFY_NON_NULL(endpoint, TAG, "endpoint is NULL");
1798 bool revertKeepAliveSetting = false;
1799 CAResult_t result = CA_STATUS_OK;
1800 oc_mutex_lock(g_mutexObjectList);
1801 CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1804 // There is no connection with the given endpoint, so the parameter is considered to be invalid.
1805 result = CA_STATUS_INVALID_PARAM;
1809 if (svritem->fd < 0 || svritem->state != CONNECTED)
1811 result = CA_DESTINATION_DISCONNECTED;
1816 if (-1 == setsockopt(svritem->fd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option)))
1818 OIC_LOG_V(ERROR, TAG, "setsockopt SO_KEEPALIVE failed on socket(%d): %s",
1819 svritem->fd, strerror(errno));
1820 result = CA_SOCKET_OPERATION_FAILED;
1824 if (-1 == setsockopt(svritem->fd, SOL_TCP, TCP_KEEPIDLE, &time, sizeof(time)))
1826 OIC_LOG_V(ERROR, TAG, "setsockopt TCP_KEEPIDLE failed on socket(%d): %s",
1827 svritem->fd, strerror(errno));
1828 revertKeepAliveSetting = true;
1829 result = CA_SOCKET_OPERATION_FAILED;
1833 if (-1 == setsockopt(svritem->fd, SOL_TCP, TCP_KEEPCNT, &cnt, sizeof(cnt)))
1835 OIC_LOG_V(ERROR, TAG, "setsockopt TCP_KEEPCNT failed on socket(%d): %s",
1836 svritem->fd, strerror(errno));
1837 revertKeepAliveSetting = true;
1838 result = CA_SOCKET_OPERATION_FAILED;
1842 if (-1 == setsockopt(svritem->fd, SOL_TCP, TCP_KEEPINTVL, &intvl, sizeof(intvl)))
1844 OIC_LOG_V(ERROR, TAG, "setsockopt TCP_KEEPINTVL failed on socket(%d): %s",
1845 svritem->fd, strerror(errno));
1846 revertKeepAliveSetting = true;
1847 result = CA_SOCKET_OPERATION_FAILED;
1851 if (revertKeepAliveSetting)
1853 // Unset SO_KEEPALIVE
1855 if (-1 == setsockopt(svritem->fd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option)))
1857 OIC_LOG_V(ERROR, TAG, "unset SO_KEEPALIVE failed on socket(%d): %s",
1858 svritem->fd, strerror(errno));
1861 oc_mutex_unlock(g_mutexObjectList);
1862 OIC_LOG(INFO, TAG, "OUT - CATCPSetKeepAlive");
1866 CAResult_t CAUnSetKeepAlive(const CAEndpoint_t *endpoint)
1868 OIC_LOG(INFO, TAG, "IN - CATCPUnSetKeepAlive");
1870 VERIFY_NON_NULL(endpoint, TAG, "endpoint is NULL");
1873 CAResult_t result = CA_STATUS_OK;
1874 oc_mutex_lock(g_mutexObjectList);
1875 CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index);
1878 // There is no connection with the given endpoint, so the parameter is considered to be invalid.
1879 result = CA_STATUS_INVALID_PARAM;
1883 if (svritem->fd < 0 || svritem->state != CONNECTED)
1885 result = CA_DESTINATION_DISCONNECTED;
1890 if (-1 == setsockopt(svritem->fd, SOL_SOCKET, SO_KEEPALIVE, &option, sizeof(option)))
1892 OIC_LOG_V(ERROR, TAG, "setsockopt SO_KEEPALIVE failed on socket(%d): %s",
1893 svritem->fd, strerror(errno));
1894 result = CA_SOCKET_OPERATION_FAILED;
1898 oc_mutex_unlock(g_mutexObjectList);
1899 OIC_LOG(INFO, TAG, "OUT - CATCPUnSetKeepAlive");
1903 int CAGetLastErrorCode()
1905 return g_lastErrorCode;