X-Git-Url: http://review.tizen.org/git/?a=blobdiff_plain;f=resource%2Fcsdk%2Fconnectivity%2Fsrc%2Ftcp_adapter%2Fcatcpserver.c;h=8ba71895fe3f88de1ef8b12cf27cc3f6e4815f24;hb=b9f147a837d6947528ac9440d2d39fd47a68ed5f;hp=4fb8c2738bc958a402504aa402c2010d97e697bd;hpb=8f51e668ae78cb8ea4e57576160ab99ddcd40a81;p=platform%2Fupstream%2Fiotivity.git diff --git a/resource/csdk/connectivity/src/tcp_adapter/catcpserver.c b/resource/csdk/connectivity/src/tcp_adapter/catcpserver.c index 4fb8c27..8ba7189 100644 --- a/resource/csdk/connectivity/src/tcp_adapter/catcpserver.c +++ b/resource/csdk/connectivity/src/tcp_adapter/catcpserver.c @@ -22,7 +22,12 @@ #include #include #include +#ifdef __TIZENRT__ +#include +#include +#else #include +#endif #include #include #include @@ -38,19 +43,22 @@ #endif #include "catcpinterface.h" -#include "pdu.h" +#include "caipnwmonitor.h" +#include #include "caadapterutils.h" -#include "camutex.h" +#include "octhread.h" #include "oic_malloc.h" +#include "oic_string.h" #ifdef __WITH_TLS__ -#include "ca_adapter_net_tls.h" +#include "ca_adapter_net_ssl.h" #endif /** * Logging tag for module name. */ -#define TAG "OIC_CA_TCP_SERVER" +//#define TAG "OIC_CA_TCP_SERVER" +#define TAG TCP_SERVER_TAG /** * Maximum CoAP over TCP header length @@ -64,14 +72,38 @@ #define TLS_HEADER_SIZE 5 /** + * Max Connection Counts. + */ +#define MAX_CONNECTION_COUNTS 500 + +#define COAP_TCP_MAX_BUFFER_CHUNK_SIZE 65530 //64kb - 6 (coap+tcp max header size) + +#define MILLISECONDS_PER_SECOND (1000) + +/** + * Thread pool. + */ +static ca_thread_pool_t g_threadPool = NULL; + +/** * Mutex to synchronize device object list. */ -static ca_mutex g_mutexObjectList = NULL; +static oc_mutex g_mutexObjectList = NULL; /** * Conditional mutex to synchronize. */ -static ca_cond g_condObjectList = NULL; +static oc_cond g_condObjectList = NULL; + +/** + * Mutex to synchronize send. + */ +static oc_mutex g_mutexSend = NULL; + +/** + * Conditional mutex to synchronize send. + */ +static oc_cond g_condSend = NULL; /** * Maintains the callback to be notified when data received from remote device. @@ -88,85 +120,117 @@ static CATCPErrorHandleCallback g_tcpErrorHandler = NULL; */ static CATCPConnectionHandleCallback g_connectionCallback = NULL; -static CAResult_t CATCPCreateMutex(); -static void CATCPDestroyMutex(); -static CAResult_t CATCPCreateCond(); -static void CATCPDestroyCond(); -static int CACreateAcceptSocket(int family, CASocket_t *sock); +static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock); static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock); static void CAFindReadyMessage(); static void CASelectReturned(fd_set *readFds); static void CAReceiveMessage(int fd); static void CAReceiveHandler(void *data); -static int CATCPCreateSocket(int family, CATCPSessionInfo_t *tcpServerInfo); +static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem); +static void CATCPInitializeSocket(); +static CATCPSessionInfo_t *CAGetSessionInfoFromFDAsOwner(int fd, size_t *index); + +#if defined(__TIZEN__) +static char g_cloudproxyUri[CA_MAX_URI_LENGTH]; + +CAResult_t CASetCloudAddressForProxy(const char *uri) +{ + if (uri == NULL) + memset(g_cloudproxyUri, '\0', sizeof (g_cloudproxyUri)); + else + OICStrcpy(g_cloudproxyUri, sizeof (g_cloudproxyUri), uri); + return CA_STATUS_OK; +} + +const char *CAGetCloudAddressForProxy() +{ + if (g_cloudproxyUri[0] == '\0') + return NULL; + return g_cloudproxyUri; +} +#endif #define CHECKFD(FD) \ if (FD > caglobals.tcp.maxfd) \ caglobals.tcp.maxfd = FD; -/** - * Read length amount of data from socket item->fd - * Can read less data length then requested - * Actual read length added to item->len variable - * - * @param[in/out] item - used socket, buffer and to update received message length - * @param[in] length - length of data required to read - * @param[in] flags - additional info about socket - * @return - CA_STATUS_OK or appropriate error code - */ -static CAResult_t CARecv(CATCPSessionInfo_t *item, size_t length, int flags) +#define CLOSE_SOCKET(TYPE) \ + if (caglobals.tcp.TYPE.fd != OC_INVALID_SOCKET) \ + { \ + close(caglobals.tcp.TYPE.fd); \ + caglobals.tcp.TYPE.fd = OC_INVALID_SOCKET; \ + } + +#define CA_FD_SET(TYPE, FDS) \ + if (caglobals.tcp.TYPE.fd != OC_INVALID_SOCKET) \ + { \ + FD_SET(caglobals.tcp.TYPE.fd, FDS); \ + } + +void CATCPDestroyMutex() { - if (NULL == item) + if (g_mutexObjectList) { - return CA_STATUS_INVALID_PARAM; + oc_mutex_free(g_mutexObjectList); + g_mutexObjectList = NULL; } +} - //skip read operation if requested zero length - if (0 == length) +CAResult_t CATCPCreateMutex() +{ + if (!g_mutexObjectList) { - return CA_STATUS_OK; + g_mutexObjectList = oc_mutex_new(); + if (!g_mutexObjectList) + { + OIC_LOG(ERROR, TAG, "Failed to create mutex!"); + return CA_STATUS_FAILED; + } } - unsigned char *buffer = item->data + item->len; - - int len = recv(item->fd, buffer, length, flags); + return CA_STATUS_OK; +} - if (len < 0) +void CATCPDestroyCond() +{ + if (g_condObjectList) { - OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno)); - return CA_RECEIVE_FAILED; + oc_cond_free(g_condObjectList); + g_condObjectList = NULL; } - else if (0 == len) +} + +CAResult_t CATCPCreateCond() +{ + if (!g_condObjectList) { - OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection"); - return CA_DESTINATION_DISCONNECTED; + g_condObjectList = oc_cond_new(); + if (!g_condObjectList) + { + OIC_LOG(ERROR, TAG, "Failed to create cond!"); + return CA_STATUS_FAILED; + } } - - OIC_LOG_V(DEBUG, TAG, "recv len = %d", len); - OIC_LOG_BUFFER(DEBUG, TAG, buffer, len); - - item->len += len; - return CA_STATUS_OK; } -static void CATCPDestroyMutex() +void CATCPDestroySendMutex() { - if (g_mutexObjectList) + if (g_mutexSend) { - ca_mutex_free(g_mutexObjectList); - g_mutexObjectList = NULL; + oc_mutex_free(g_mutexSend); + g_mutexSend = NULL; } } -static CAResult_t CATCPCreateMutex() +CAResult_t CATCPCreateSendMutex() { - if (!g_mutexObjectList) + if (!g_mutexSend) { - g_mutexObjectList = ca_mutex_new(); - if (!g_mutexObjectList) + g_mutexSend = oc_mutex_new(); + if (!g_mutexSend) { - OIC_LOG(ERROR, TAG, "Failed to created mutex!"); + OIC_LOG(ERROR, TAG, "Failed to create send mutex!"); return CA_STATUS_FAILED; } } @@ -174,23 +238,23 @@ static CAResult_t CATCPCreateMutex() return CA_STATUS_OK; } -static void CATCPDestroyCond() +void CATCPDestroySendCond() { - if (g_condObjectList) + if (g_condSend) { - ca_cond_free(g_condObjectList); - g_condObjectList = NULL; + oc_cond_free(g_condSend); + g_condSend = NULL; } } -static CAResult_t CATCPCreateCond() +CAResult_t CATCPCreateSendCond() { - if (!g_condObjectList) + if (!g_condSend) { - g_condObjectList = ca_cond_new(); - if (!g_condObjectList) + g_condSend = oc_cond_new(); + if (!g_condSend) { - OIC_LOG(ERROR, TAG, "Failed to created cond!"); + OIC_LOG(ERROR, TAG, "Failed to create send cond!"); return CA_STATUS_FAILED; } } @@ -202,14 +266,21 @@ static void CAReceiveHandler(void *data) (void)data; OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler"); - while (!caglobals.tcp.terminate) + while (true) { + oc_mutex_lock(g_mutexObjectList); + if (caglobals.tcp.terminate) + { + oc_mutex_unlock(g_mutexObjectList); + break; + } + oc_mutex_unlock(g_mutexObjectList); CAFindReadyMessage(); } - ca_mutex_lock(g_mutexObjectList); - ca_cond_signal(g_condObjectList); - ca_mutex_unlock(g_mutexObjectList); + oc_mutex_lock(g_mutexObjectList); + oc_cond_signal(g_condObjectList); + oc_mutex_unlock(g_mutexObjectList); OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler"); } @@ -220,20 +291,17 @@ static void CAFindReadyMessage() struct timeval timeout = { .tv_sec = caglobals.tcp.selectTimeout }; FD_ZERO(&readFds); - - if (-1 != caglobals.tcp.ipv4.fd) - { - FD_SET(caglobals.tcp.ipv4.fd, &readFds); - } - if (-1 != caglobals.tcp.ipv6.fd) - { - FD_SET(caglobals.tcp.ipv6.fd, &readFds); - } - if (-1 != caglobals.tcp.shutdownFds[0]) + CA_FD_SET(ipv4, &readFds); + CA_FD_SET(ipv4s, &readFds); + CA_FD_SET(ipv6, &readFds); + CA_FD_SET(ipv6s, &readFds); +#ifndef __TIZENRT__ + if (OC_INVALID_SOCKET != caglobals.tcp.shutdownFds[0]) { FD_SET(caglobals.tcp.shutdownFds[0], &readFds); } - if (-1 != caglobals.tcp.connectionFds[0]) +#endif + if (OC_INVALID_SOCKET != caglobals.tcp.connectionFds[0]) { FD_SET(caglobals.tcp.connectionFds[0], &readFds); } @@ -243,7 +311,7 @@ static void CAFindReadyMessage() { CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i); - if (svritem && 0 <= svritem->fd) + if (svritem && 0 <= svritem->fd && CONNECTED == svritem->state) { FD_SET(svritem->fd, &readFds); } @@ -251,11 +319,14 @@ static void CAFindReadyMessage() int ret = select(caglobals.tcp.maxfd + 1, &readFds, NULL, NULL, &timeout); + oc_mutex_lock(g_mutexObjectList); if (caglobals.tcp.terminate) { - OIC_LOG_V(DEBUG, TAG, "Packet receiver Stop request received."); + oc_mutex_unlock(g_mutexObjectList); + OIC_LOG_V(INFO, TAG, "Packet receiver Stop request received."); return; } + oc_mutex_unlock(g_mutexObjectList); if (0 >= ret) { if (0 > ret) @@ -277,11 +348,21 @@ static void CASelectReturned(fd_set *readFds) CAAcceptConnection(CA_IPV4, &caglobals.tcp.ipv4); return; } + else if (caglobals.tcp.ipv4s.fd != -1 && FD_ISSET(caglobals.tcp.ipv4s.fd, readFds)) + { + CAAcceptConnection(CA_IPV4 | CA_SECURE, &caglobals.tcp.ipv4s); + return; + } else if (caglobals.tcp.ipv6.fd != -1 && FD_ISSET(caglobals.tcp.ipv6.fd, readFds)) { CAAcceptConnection(CA_IPV6, &caglobals.tcp.ipv6); return; } + else if (caglobals.tcp.ipv6s.fd != -1 && FD_ISSET(caglobals.tcp.ipv6s.fd, readFds)) + { + CAAcceptConnection(CA_IPV6 | CA_SECURE, &caglobals.tcp.ipv6s); + return; + } else if (-1 != caglobals.tcp.connectionFds[0] && FD_ISSET(caglobals.tcp.connectionFds[0], readFds)) { @@ -294,12 +375,24 @@ static void CASelectReturned(fd_set *readFds) return; } OIC_LOG_V(DEBUG, TAG, "Received new connection event with [%s]", buf); - FD_CLR(caglobals.tcp.connectionFds[0], readFds); return; } else { + int *readFDList = NULL; + size_t readFDListSize = 0; + + oc_mutex_lock(g_mutexObjectList); uint32_t length = u_arraylist_length(caglobals.tcp.svrlist); + + readFDList = (int*) OICCalloc(length, sizeof(int)); + if (NULL == readFDList) + { + OIC_LOG_V(ERROR, TAG, "Failed to allocate memory!"); + oc_mutex_unlock(g_mutexObjectList); + return; + } + for (size_t i = 0; i < length; i++) { CATCPSessionInfo_t *svritem = @@ -308,18 +401,35 @@ static void CASelectReturned(fd_set *readFds) { if (FD_ISSET(svritem->fd, readFds)) { - CAReceiveMessage(svritem->fd); - FD_CLR(svritem->fd, readFds); + readFDList[readFDListSize++] = svritem->fd; } } } + oc_mutex_unlock(g_mutexObjectList); + + // Read incomming messages from fds + for (size_t i = 0; i < readFDListSize; i++) + { + CAReceiveMessage(readFDList[i]); + } + + OICFree(readFDList); } } static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock) { + OIC_LOG_V(INFO, TAG, "In %s", __func__); VERIFY_NON_NULL_VOID(sock, TAG, "sock is NULL"); + if (MAX_CONNECTION_COUNTS == u_arraylist_length(caglobals.tcp.svrlist)) + { + OIC_LOG_V(INFO, TAG, "Exceeding the max connection counts limit, close listening port"); + close(sock->fd); + sock->fd = OC_INVALID_SOCKET; + return; + } + struct sockaddr_storage clientaddr; socklen_t clientlen = sizeof (struct sockaddr_in); if (flag & CA_IPV6) @@ -327,8 +437,8 @@ static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock) clientlen = sizeof(struct sockaddr_in6); } - int sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen); - if (-1 != sockfd) + CASocketFd_t sockfd = accept(sock->fd, (struct sockaddr *)&clientaddr, &clientlen); + if (OC_INVALID_SOCKET != sockfd) { CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem)); @@ -341,86 +451,91 @@ static void CAAcceptConnection(CATransportFlags_t flag, CASocket_t *sock) svritem->fd = sockfd; svritem->sep.endpoint.flags = flag; + svritem->sep.endpoint.adapter = CA_ADAPTER_TCP; + svritem->state = CONNECTED; + svritem->isClient = false; CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen, svritem->sep.endpoint.addr, &svritem->sep.endpoint.port); - ca_mutex_lock(g_mutexObjectList); + // Allocate message buffer + svritem->tlsdata = (unsigned char*) OICCalloc(TLS_DATA_MAX_SIZE, sizeof(unsigned char)); + if (!svritem->tlsdata) + { + OIC_LOG(ERROR, TAG, "Out of memory"); + close(sockfd); + OICFree(svritem); + return; + } + + oc_mutex_lock(g_mutexObjectList); bool result = u_arraylist_add(caglobals.tcp.svrlist, svritem); if (!result) { OIC_LOG(ERROR, TAG, "u_arraylist_add failed."); close(sockfd); + OICFree(svritem->tlsdata); OICFree(svritem); - ca_mutex_unlock(g_mutexObjectList); + oc_mutex_unlock(g_mutexObjectList); return; } - ca_mutex_unlock(g_mutexObjectList); + oc_mutex_unlock(g_mutexObjectList); CHECKFD(sockfd); - } -} - -#ifdef __WITH_TLS__ -static bool CAIsTlsMessage(const unsigned char* data, size_t length) -{ - if (NULL == data || 0 == length) - { - OIC_LOG_V(ERROR, TAG, "%s: null input param", __func__); - return false; - } - - unsigned char first_byte = data[0]; - //TLS Plaintext has four types: change_cipher_spec = [14], alert = [15], - //handshake = [16], application_data = [17] in HEX - const uint8_t tls_head_type[] = {0x14, 0x15, 0x16, 0x17}; - size_t i = 0; - - for (i = 0; i < sizeof(tls_head_type); i++) - { - if(tls_head_type[i] == first_byte) + // pass the connection information to CA Common Layer. + if (g_connectionCallback) { - return true; + g_connectionCallback(&(svritem->sep.endpoint), true, svritem->isClient); } } - - return false; + OIC_LOG_V(INFO, TAG, "Out %s", __func__); } -#endif /** * Clean socket state data * * @param[in/out] item - socket state data */ -static void CACleanData(CATCPSessionInfo_t *svritem) +void CACleanData(CATCPSessionInfo_t *svritem) { if (svritem) { OICFree(svritem->data); svritem->data = NULL; svritem->len = 0; +#ifdef __WITH_TLS__ + svritem->tlsLen = 0; +#endif svritem->totalLen = 0; + svritem->bufLen = 0; svritem->protocol = UNKNOWN; } } /** - * Read message header from socket item->fd + * Construct CoAP header and payload from buffer * - * @param[in/out] item - used socket, buffer, current received message length and protocol + * @param[in] svritem - used socket, buffer, current received message length and protocol + * @param[in/out] data - data buffer, this value is updated as data is copied to svritem + * @param[in/out] dataLength - length of data, this value decreased as data is copied to svritem * @return - CA_STATUS_OK or appropriate error code */ -static CAResult_t CAReadHeader(CATCPSessionInfo_t *svritem) +CAResult_t CAConstructCoAP(CATCPSessionInfo_t *svritem, unsigned char **data, + size_t *dataLength) { - CAResult_t res = CA_STATUS_OK; + OIC_LOG_V(DEBUG, TAG, "In %s", __func__); - if (NULL == svritem) + if (NULL == svritem || NULL == data || NULL == dataLength) { + OIC_LOG(ERROR, TAG, "Invalid input parameter(NULL)"); return CA_STATUS_INVALID_PARAM; } - if (NULL == svritem->data) + unsigned char *inBuffer = *data; + size_t inLen = *dataLength; + OIC_LOG_V(DEBUG, TAG, "before-datalength : %zd", *dataLength); + + if (NULL == svritem->data && inLen > 0) { // allocate memory for message header (CoAP header size because it is bigger) svritem->data = (unsigned char *) OICCalloc(1, COAP_MAX_HEADER_SIZE); @@ -429,176 +544,254 @@ static CAResult_t CAReadHeader(CATCPSessionInfo_t *svritem) OIC_LOG(ERROR, TAG, "OICCalloc - out of memory"); return CA_MEMORY_ALLOC_FAILED; } - } - //read data (assume TLS header) from remote device. - //use TLS_HEADER_SIZE - svritem->len because even header can be read partially - res = CARecv(svritem, TLS_HEADER_SIZE - svritem->len, 0); - - //return if any error occurs - if (CA_STATUS_OK != res) - { - return res; + // copy 1 byte to parse coap header length + memcpy(svritem->data, inBuffer, 1); + svritem->len = 1; + svritem->bufLen = COAP_MAX_HEADER_SIZE; + inBuffer++; + inLen--; } - //if not enough data received - read them on next CAReceiveMessage() call - if (svritem->len < TLS_HEADER_SIZE) + //if not enough data received - read them on next CAFillHeader() call + if (0 == inLen) { - OIC_LOG(DEBUG, TAG, "Header received partially. Wait for rest header data"); return CA_STATUS_OK; } //if enough data received - parse header -#ifdef __WITH_TLS__ - if (CAIsTlsMessage(svritem->data, svritem->len)) - { - svritem->protocol = TLS; + svritem->protocol = COAP; - //[3][4] bytes in tls header are tls payload length - unsigned int message_length = (unsigned int)((svritem->data[3] << 8) | svritem->data[4]); - OIC_LOG_V(DEBUG, TAG, "%s: message_length = %d", __func__, message_length); + //seems CoAP data received. read full coap header. + coap_transport_t transport = coap_get_tcp_header_type_from_initbyte(svritem->data[0] >> 4); + size_t headerLen = coap_get_tcp_header_length_for_transport(transport); + size_t copyLen = 0; - svritem->totalLen = message_length + TLS_HEADER_SIZE; - } - else -#endif + // HEADER + if (svritem->len < headerLen) { - svritem->protocol = COAP; - - //seems CoAP data received. read full coap header. - coap_transport_type transport = coap_get_tcp_header_type_from_initbyte(svritem->data[0] >> 4); + copyLen = headerLen - svritem->len; + if (inLen < copyLen) + { + copyLen = inLen; + } - size_t headerLen = coap_get_tcp_header_length_for_transport(transport); + //read required bytes to have full CoAP header + memcpy(svritem->data + svritem->len, inBuffer, copyLen); + svritem->len += copyLen; + inBuffer += copyLen; + inLen -= copyLen; + //if not enough data received - read them on next CAFillHeader() call if (svritem->len < headerLen) { - //read required bytes to have full CoAP header - //it should be 1 byte (COAP_MAX_HEADER_SIZE - TLS_HEADER_SIZE) - res = CARecv(svritem, headerLen - svritem->len, 0); - - //return if any error occurs - if (CA_STATUS_OK != res) - { - return res; - } - - //if not enough data received - read them on next CAReceiveMessage() call - if (svritem->len < headerLen) - { - OIC_LOG(DEBUG, TAG, "CoAP header received partially. Wait for rest header data"); - return CA_STATUS_OK; - } + *data = inBuffer; + *dataLength = inLen; + OIC_LOG(DEBUG, TAG, "CoAP header received partially. Wait for rest header data"); + return CA_STATUS_OK; } //calculate CoAP message length svritem->totalLen = CAGetTotalLengthFromHeader(svritem->data); } - unsigned char *buffer = OICRealloc(svritem->data, svritem->totalLen); - if (NULL == buffer) + // PAYLOAD + if (inLen > 0) { - OIC_LOG(ERROR, TAG, "OICRealloc - out of memory"); - return CA_MEMORY_ALLOC_FAILED; - } - svritem->data = buffer; - - return CA_STATUS_OK; -} - -/** - * Read message payload from socket item->fd - - * - * @param[in/out] item - used socket, buffer and to update received message length - * @return - CA_STATUS_OK or appropriate error code - */ -static CAResult_t CAReadPayload(CATCPSessionInfo_t *svritem) -{ - if (NULL == svritem) - { - return CA_STATUS_INVALID_PARAM; - } - - return CARecv(svritem, svritem->totalLen - svritem->len, 0); -} - -/** - * Pass received data to app layer depending on protocol - * - * @param[in/out] item - used buffer, received message length and protocol - */ -static void CAExecuteRequest(CATCPSessionInfo_t *svritem) -{ - if (NULL == svritem) - { - return; - } + // Calculate length of data to be copied. + copyLen = svritem->totalLen - svritem->len; + if (inLen < copyLen) + { + copyLen = inLen; + } - switch(svritem->protocol) - { - case COAP: + // Is buffer not big enough for remaining data ? + if (svritem->len + copyLen > svritem->bufLen) { - if (g_packetReceivedCallback) + // Resize buffer to accommodate enough space + size_t extLen = svritem->totalLen - svritem->bufLen; + if (extLen > COAP_TCP_MAX_BUFFER_CHUNK_SIZE) { - g_packetReceivedCallback(&svritem->sep, svritem->data, svritem->len); + extLen = COAP_TCP_MAX_BUFFER_CHUNK_SIZE; } - } - break; - case TLS: -#ifdef __WITH_TLS__ - { - int ret = CAdecryptTls(&svritem->sep, (uint8_t *)svritem->data, svritem->len); - OIC_LOG_V(DEBUG, TAG, "%s: CAdecryptTls returned %d", __func__, ret); + // Allocate required memory + unsigned char *buffer = OICRealloc(svritem->data, svritem->bufLen + extLen); + if (NULL == buffer) + { + OIC_LOG(ERROR, TAG, "OICRealloc - out of memory"); + return CA_MEMORY_ALLOC_FAILED; + } + + svritem->data = buffer; + svritem->bufLen += extLen; } - break; -#endif - case UNKNOWN: /* pass through */ - default: - OIC_LOG(ERROR, TAG, "unknown application protocol. Ignore it"); - break; + + // Read required bytes to have full CoAP payload + memcpy(svritem->data + svritem->len, inBuffer, copyLen); + svritem->len += copyLen; + inBuffer += copyLen; + inLen -= copyLen; } + + *data = inBuffer; + *dataLength = inLen; + + OIC_LOG_V(DEBUG, TAG, "after-datalength : %zd", *dataLength); + OIC_LOG_V(DEBUG, TAG, "Out %s", __func__); + return CA_STATUS_OK; } static void CAReceiveMessage(int fd) { CAResult_t res = CA_STATUS_OK; + oc_mutex_lock(g_mutexObjectList); + //get remote device information from file descriptor. size_t index = 0; - CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFD(fd, &index); + CATCPSessionInfo_t *svritem = CAGetSessionInfoFromFDAsOwner(fd, &index); if (!svritem) { OIC_LOG(ERROR, TAG, "there is no connection information in list"); + oc_mutex_unlock(g_mutexObjectList); return; } - //totalLen filled only when header fully read and parsed - if (0 == svritem->totalLen) + CASecureEndpoint_t peerEP = svritem->sep; + int len = 0; + if (svritem->sep.endpoint.flags & CA_SECURE) // Secure connection { - res = CAReadHeader(svritem); + svritem->protocol = TLS; + +#ifdef __WITH_TLS__ + size_t nbRead = 0; + size_t tlsLength = 0; + + if (TLS_HEADER_SIZE > svritem->tlsLen) + { + nbRead = TLS_HEADER_SIZE - svritem->tlsLen; + } + else + { + //[3][4] bytes in tls header are tls payload length + tlsLength = TLS_HEADER_SIZE + + (size_t)((svritem->tlsdata[3] << 8) | svritem->tlsdata[4]); + OIC_LOG_V(DEBUG, TAG, "total tls length = %zd", tlsLength); + if (tlsLength > TLS_DATA_MAX_SIZE) + { + OIC_LOG_V(ERROR, TAG, "total tls length is too big (buffer size : %u)", + TLS_DATA_MAX_SIZE); + oc_mutex_unlock(g_mutexObjectList); + CATCPDisconnectSession(&peerEP.endpoint); + return; + } + nbRead = tlsLength - svritem->tlsLen; + } + + len = recv(fd, svritem->tlsdata + svritem->tlsLen, nbRead, 0); + if (len < 0) + { + OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno)); + res = CA_RECEIVE_FAILED; + } + else if (0 == len) + { + OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection"); + svritem->state = DISCONNECTED; + res = CA_DESTINATION_DISCONNECTED; + } + else + { + svritem->tlsLen += len; + OIC_LOG_V(DEBUG, TAG, "nb_read : %zd bytes , recv() : %d bytes, svritem->tlsLen : %zd bytes", + nbRead, len, svritem->tlsLen); + if (tlsLength > 0 && tlsLength == svritem->tlsLen) + { + // When successfully read data - pass them to callback. + // Dont invoke callback locking mutex + unsigned char *mesBuf = svritem->tlsdata; + size_t mesBufLen = svritem->tlsLen; + svritem->tlsdata = NULL; + oc_mutex_unlock(g_mutexObjectList); + + res = CAdecryptSsl(&peerEP, (uint8_t *)mesBuf, mesBufLen); + OIC_LOG_V(INFO, TAG, "%s: CAdecryptSsl returned %d", __func__, res); + + // Check for the svritem and reset buffer + oc_mutex_lock(g_mutexObjectList); + svritem = CAGetSessionInfoFromFDAsOwner(fd, &index); + if (svritem) + { + svritem->tlsdata = mesBuf; + svritem->tlsLen = 0; + } + else + { + // svritem does not exist, thus free the message buffer + OIC_LOG(ERROR, TAG, "svritem not found. Freeing message buffer!"); + OICFree(mesBuf); + } + } + } +#endif } - else + else // Non-Secure connection { - res = CAReadPayload(svritem); + svritem->protocol = COAP; - //when successfully read all required data - pass them to upper layer. - if (CA_STATUS_OK == res && svritem->len == svritem->totalLen) + // svritem->tlsdata can also be used as receiving buffer in case of raw tcp + len = recv(fd, svritem->tlsdata, TLS_DATA_MAX_SIZE, 0); + if (len < 0) { - CAExecuteRequest(svritem); - CACleanData(svritem); + OIC_LOG_V(ERROR, TAG, "recv failed %s", strerror(errno)); + res = CA_RECEIVE_FAILED; + } + else if (0 == len) + { + OIC_LOG(INFO, TAG, "Received disconnect from peer. Close connection"); + res = CA_DESTINATION_DISCONNECTED; + } + else + { + //when successfully read data - pass them to callback. + OIC_LOG_V(DEBUG, TAG, "recv() : %d bytes", len); + if (g_packetReceivedCallback) + { + // Dont invoke callback locking mutex + unsigned char *mesBuf = svritem->tlsdata; + svritem->tlsdata = NULL; + oc_mutex_unlock(g_mutexObjectList); + + res = g_packetReceivedCallback(&peerEP, mesBuf, len); + + // Check for the svritem and reset buffer + oc_mutex_lock(g_mutexObjectList); + svritem = CAGetSessionInfoFromFDAsOwner(fd, &index); + if (svritem) + { + svritem->tlsdata = mesBuf; + svritem->tlsLen = 0; + } + else + { + // svritem does not exist, thus free the message buffer + OIC_LOG(ERROR, TAG, "svritem not found. Freeing message buffer!"); + OICFree(mesBuf); + } + } } } - //disconnect session and clean-up data if any error occurs + oc_mutex_unlock(g_mutexObjectList); + if (res != CA_STATUS_OK) { - CADisconnectTCPSession(svritem, index); - CACleanData(svritem); + CATCPDisconnectSession(&peerEP.endpoint); } } -static void CAWakeUpForReadFdsUpdate(const char *host) +static ssize_t CAWakeUpForReadFdsUpdate(const char *host) { if (caglobals.tcp.connectionFds[1] != -1) { @@ -612,7 +805,9 @@ static void CAWakeUpForReadFdsUpdate(const char *host) { OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno)); } + return len; } + return -1; } static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t port, @@ -654,15 +849,36 @@ static CAResult_t CATCPConvertNameToAddr(int family, const char *host, uint16_t return CA_STATUS_OK; } -static int CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem) +#if defined(__TIZEN__) +static int CAGetHTTPStatusCode(char * response) { + char *resp, *code_plus, *ptrSave; + int ret = -1; + + resp = strdup(response); + strtok_r(resp, " ", &ptrSave); /* skip HTTP version */ + code_plus = strtok_r(NULL, " ", &ptrSave); + + ret = code_plus ? atoi(code_plus) : -1; + free(resp); + return ret; +} +#endif + +static CAResult_t CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem) { + VERIFY_NON_NULL(svritem, TAG, "svritem is NULL"); + + OIC_LOG_V(INFO, TAG, "try to connect with [%s:%u]", + svritem->sep.endpoint.addr, svritem->sep.endpoint.port); + // #1. create tcp socket. int fd = socket(family, SOCK_STREAM, IPPROTO_TCP); if (-1 == fd) { OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno)); - return -1; + return CA_SOCKET_OPERATION_FAILED; } + svritem->fd = fd; // #2. convert address from string to binary. struct sockaddr_storage sa = { .ss_family = family }; @@ -670,8 +886,8 @@ static int CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem) svritem->sep.endpoint.port, &sa); if (CA_STATUS_OK != res) { - close(fd); - return -1; + OIC_LOG(ERROR, TAG, "convert name to sockaddr failed"); + return CA_SOCKET_OPERATION_FAILED; } // #3. set socket length. @@ -694,20 +910,76 @@ static int CATCPCreateSocket(int family, CATCPSessionInfo_t *svritem) if (connect(fd, (struct sockaddr *)&sa, socklen) < 0) { OIC_LOG_V(ERROR, TAG, "failed to connect socket, %s", strerror(errno)); - close(fd); - return -1; + CALogSendStateInfo(svritem->sep.endpoint.adapter, svritem->sep.endpoint.addr, + svritem->sep.endpoint.port, 0, false, strerror(errno)); + return CA_SOCKET_OPERATION_FAILED; } - OIC_LOG(DEBUG, TAG, "connect socket success"); - CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr); - return fd; + OIC_LOG(INFO, TAG, "connect socket success"); + svritem->state = CONNECTED; + CHECKFD(svritem->fd); + ssize_t len = CAWakeUpForReadFdsUpdate(svritem->sep.endpoint.addr); + if (-1 == len) + { + OIC_LOG(ERROR, TAG, "wakeup receive thread failed"); + return CA_SOCKET_OPERATION_FAILED; + } + +#if defined(__TIZEN__) + // #5. Send HTTP CONNECT to proxy if proxy + + const char *cloud_address = CAGetCloudAddressForProxy(); + OIC_LOG_V(INFO, TAG, "Proxy : '%s'", cloud_address ? cloud_address : "(nil)"); + + if(cloud_address && *cloud_address) + { + char message[4096]; + int len = sprintf(message, + "CONNECT %s HTTP/1.1\r\n" + "Host: %s\r\n\r\n", cloud_address, cloud_address + ); + + ssize_t l = send(fd, message, len, 0); + if(l != len) + { + OIC_LOG_V(ERROR, TAG, "failed to send HTTP CONNECT data (expected %d bytes, ret %zd)", len, l); + close(fd); + svritem->fd = -1; + return CA_SOCKET_OPERATION_FAILED; + } + + // maybe this should be called in other thread, it causes bottleneck. + OIC_LOG_V(INFO, TAG, "Message sent is : '%s'\n", message); + + *message = '\0'; + OIC_LOG_V(INFO, TAG, "Receiving response to CONNECT from proxy..."); + + l = recv(fd, message, 4096, 0); + + OIC_LOG_V(INFO, TAG, "Received data : '%s'", message); + OIC_LOG_V(INFO, TAG, "Received len = %zd", l); + + int status_code = CAGetHTTPStatusCode(message); + + OIC_LOG_V(INFO, TAG, "HTTP status_code : %d", status_code); + if(status_code < 200 || status_code > 299) + { + OIC_LOG_V(ERROR, TAG, "Error, Wrong status code: %d", status_code); + close(fd); + svritem->fd = -1; + return CA_SOCKET_OPERATION_FAILED; + } + } +#endif + + return CA_STATUS_OK; } -static int CACreateAcceptSocket(int family, CASocket_t *sock) +static CASocketFd_t CACreateAcceptSocket(int family, CASocket_t *sock) { VERIFY_NON_NULL_RET(sock, TAG, "sock", -1); - if (sock->fd != -1) + if (OC_INVALID_SOCKET != sock->fd) { OIC_LOG(DEBUG, TAG, "accept socket created already"); return sock->fd; @@ -717,7 +989,7 @@ static int CACreateAcceptSocket(int family, CASocket_t *sock) struct sockaddr_storage server = { .ss_family = family }; int fd = socket(family, SOCK_STREAM, IPPROTO_TCP); - if (fd < 0) + if (OC_INVALID_SOCKET == fd) { OIC_LOG(ERROR, TAG, "Failed to create socket"); goto exit; @@ -725,13 +997,16 @@ static int CACreateAcceptSocket(int family, CASocket_t *sock) if (family == AF_INET6) { - // the socket is re‐stricted to sending and receiving IPv6 packets only. + // the socket is restricted to sending and receiving IPv6 packets only. int on = 1; +//TODO: enable once IPv6 is supported +#ifndef __TIZENRT__ if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on))) { OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno)); goto exit; } +#endif ((struct sockaddr_in6 *)&server)->sin6_port = htons(sock->port); socklen = sizeof (struct sockaddr_in6); } @@ -760,7 +1035,17 @@ static int CACreateAcceptSocket(int family, CASocket_t *sock) goto exit; } - if (!sock->port) // return the assigned port + if (sock->port) // use the given port + { + int on = 1; + if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof (on))) + { + OIC_LOG_V(ERROR, TAG, "SO_REUSEADDR failed: %s", strerror(errno)); + close(fd); + return OC_INVALID_SOCKET; + } + } + else // return the assigned port { if (-1 == getsockname(fd, (struct sockaddr *)&server, &socklen)) { @@ -779,12 +1064,26 @@ exit: { close(fd); } - return -1; + return OC_INVALID_SOCKET; } static void CAInitializePipe(int *fds) { int ret = pipe(fds); +// TODO: Remove temporary workaround once F_GETFD / F_SETFD support is in TizenRT +/* Temporary workaround: By pass F_GETFD / F_SETFD */ +#ifdef __TIZENRT__ + if (-1 == ret) + { + close(fds[1]); + close(fds[0]); + + fds[0] = -1; + fds[1] = -1; + + OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno)); + } +#else if (-1 != ret) { ret = fcntl(fds[0], F_GETFD); @@ -811,8 +1110,10 @@ static void CAInitializePipe(int *fds) OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno)); } } +#endif } +#ifndef DISABLE_TCP_SERVER #define NEWSOCKET(FAMILY, NAME) \ caglobals.tcp.NAME.fd = CACreateAcceptSocket(FAMILY, &caglobals.tcp.NAME); \ if (caglobals.tcp.NAME.fd == -1) \ @@ -822,13 +1123,48 @@ static void CAInitializePipe(int *fds) } \ CHECKFD(caglobals.tcp.NAME.fd); +void CATCPInitializeSocket() +{ +#ifndef __WITH_TLS__ + NEWSOCKET(AF_INET, ipv4); +#else + NEWSOCKET(AF_INET, ipv4s); +#endif + +//TODO Enable once TizenRT supports IPv6 +#ifndef __TIZENRT__ +#ifndef __WITH_TLS__ + NEWSOCKET(AF_INET6, ipv6); +#else + NEWSOCKET(AF_INET6, ipv6s); +#endif +#endif +#ifndef __WITH_TLS__ + OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d", + caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port); + OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d", + caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port); +#else + OIC_LOG_V(DEBUG, TAG, "IPv4 secure socket fd=%d, port=%d", + caglobals.tcp.ipv4s.fd, caglobals.tcp.ipv4s.port); + OIC_LOG_V(DEBUG, TAG, "IPv6 secure socket fd=%d, port=%d", + caglobals.tcp.ipv6s.fd, caglobals.tcp.ipv6s.port); +#endif +} +#endif // DISABLE_TCP_SERVER + CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool) { + oc_mutex_lock(g_mutexObjectList); if (caglobals.tcp.started) { + oc_mutex_unlock(g_mutexObjectList); + OIC_LOG(INFO, TAG, "Adapter is started already"); return CA_STATUS_OK; } + g_threadPool = threadPool; + if (!caglobals.tcp.ipv4tcpenabled) { caglobals.tcp.ipv4tcpenabled = true; // only needed to run CA tests @@ -838,100 +1174,120 @@ CAResult_t CATCPStartServer(const ca_thread_pool_t threadPool) caglobals.tcp.ipv6tcpenabled = true; // only needed to run CA tests } - CAResult_t res = CATCPCreateMutex(); - if (CA_STATUS_OK == res) - { - res = CATCPCreateCond(); - } - if (CA_STATUS_OK != res) - { - OIC_LOG(ERROR, TAG, "failed to create mutex/cond"); - return res; - } - - ca_mutex_lock(g_mutexObjectList); + caglobals.tcp.terminate = false; if (!caglobals.tcp.svrlist) { caglobals.tcp.svrlist = u_arraylist_create(); } - ca_mutex_unlock(g_mutexObjectList); +#ifndef DISABLE_TCP_SERVER if (caglobals.server) { - NEWSOCKET(AF_INET, ipv4); - NEWSOCKET(AF_INET6, ipv6); - OIC_LOG_V(DEBUG, TAG, "IPv4 socket fd=%d, port=%d", - caglobals.tcp.ipv4.fd, caglobals.tcp.ipv4.port); - OIC_LOG_V(DEBUG, TAG, "IPv6 socket fd=%d, port=%d", - caglobals.tcp.ipv6.fd, caglobals.tcp.ipv6.port); + CATCPInitializeSocket(); } +#endif +#ifndef __TIZENRT__ // create pipe for fast shutdown CAInitializePipe(caglobals.tcp.shutdownFds); CHECKFD(caglobals.tcp.shutdownFds[0]); CHECKFD(caglobals.tcp.shutdownFds[1]); - +#endif // create pipe for connection event CAInitializePipe(caglobals.tcp.connectionFds); CHECKFD(caglobals.tcp.connectionFds[0]); CHECKFD(caglobals.tcp.connectionFds[1]); - caglobals.tcp.terminate = false; - res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL); + CAResult_t res = CA_STATUS_OK; +#ifndef __TIZENRT__ + res = ca_thread_pool_add_task(g_threadPool, CAReceiveHandler, NULL, NULL); +#else + res = ca_thread_pool_add_task(g_threadPool, CAReceiveHandler, NULL, NULL, + "IoT_TCPReceive", CONFIG_IOTIVITY_TCPRECEIVE_PTHREAD_STACKSIZE); +#endif if (CA_STATUS_OK != res) { + oc_mutex_unlock(g_mutexObjectList); OIC_LOG(ERROR, TAG, "thread_pool_add_task failed"); + CATCPStopServer(); return res; } - OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully."); caglobals.tcp.started = true; + oc_mutex_unlock(g_mutexObjectList); + + OIC_LOG(INFO, TAG, "CAReceiveHandler thread started successfully."); return CA_STATUS_OK; } void CATCPStopServer() { - // mutex lock - ca_mutex_lock(g_mutexObjectList); + oc_mutex_lock(g_mutexObjectList); + if (caglobals.tcp.terminate) + { + oc_mutex_unlock(g_mutexObjectList); + OIC_LOG(INFO, TAG, "Adapter is not enabled"); + return; + } - // set terminate flag + // set terminate flag. caglobals.tcp.terminate = true; - if (caglobals.tcp.shutdownFds[1] != -1) + oc_mutex_lock(g_mutexSend); + oc_cond_signal(g_condSend); + oc_mutex_unlock(g_mutexSend); + +#ifdef __TIZENRT__ + if (caglobals.tcp.started) { - close(caglobals.tcp.shutdownFds[1]); - // receive thread will stop immediately + oc_cond_wait(g_condObjectList, g_mutexObjectList); + caglobals.tcp.started = false; } +#endif - if (caglobals.tcp.connectionFds[1] != -1) + // close accept socket. +#ifndef __WITH_TLS__ + CLOSE_SOCKET(ipv4); + CLOSE_SOCKET(ipv6); +#else + CLOSE_SOCKET(ipv4s); + CLOSE_SOCKET(ipv6s); +#endif + + if (caglobals.tcp.connectionFds[1] != OC_INVALID_SOCKET) { - close(caglobals.tcp.connectionFds[1]); + close(caglobals.tcp.connectionFds[1]); + caglobals.tcp.connectionFds[1] = OC_INVALID_SOCKET; } - - if (caglobals.tcp.started) + if (caglobals.tcp.connectionFds[0] != OC_INVALID_SOCKET) { - ca_cond_wait(g_condObjectList, g_mutexObjectList); + close(caglobals.tcp.connectionFds[0]); + caglobals.tcp.connectionFds[0] = OC_INVALID_SOCKET; } - caglobals.tcp.started = false; - - // mutex unlock - ca_mutex_unlock(g_mutexObjectList); - - if (-1 != caglobals.tcp.ipv4.fd) +#ifndef __TIZENRT__ + if (caglobals.tcp.shutdownFds[1] != OC_INVALID_SOCKET) { - close(caglobals.tcp.ipv4.fd); - caglobals.tcp.ipv4.fd = -1; + close(caglobals.tcp.shutdownFds[1]); + caglobals.tcp.shutdownFds[1] = OC_INVALID_SOCKET; + // receive thread will stop immediately } - - if (-1 != caglobals.tcp.ipv6.fd) + if (caglobals.tcp.started) { - close(caglobals.tcp.ipv6.fd); - caglobals.tcp.ipv6.fd = -1; + oc_cond_wait(g_condObjectList, g_mutexObjectList); + caglobals.tcp.started = false; } + if (caglobals.tcp.shutdownFds[0] != OC_INVALID_SOCKET) + { + close(caglobals.tcp.shutdownFds[0]); + caglobals.tcp.shutdownFds[0] = OC_INVALID_SOCKET; + } +#endif + oc_mutex_unlock(g_mutexObjectList); CATCPDisconnectAll(); - CATCPDestroyMutex(); - CATCPDestroyCond(); + sleep(1); + + OIC_LOG(INFO, TAG, "Adapter terminated successfully"); } void CATCPSetPacketReceiveCallback(CATCPPacketReceivedCallback callback) @@ -944,21 +1300,22 @@ void CATCPSetConnectionChangedCallback(CATCPConnectionHandleCallback connHandler g_connectionCallback = connHandler; } -static size_t CACheckPayloadLength(const void *data, size_t dlen) +size_t CACheckPayloadLengthFromHeader(const void *data, size_t dlen) { VERIFY_NON_NULL_RET(data, TAG, "data", -1); - coap_transport_type transport = coap_get_tcp_header_type_from_initbyte( + coap_transport_t transport = coap_get_tcp_header_type_from_initbyte( ((unsigned char *)data)[0] >> 4); - coap_pdu_t *pdu = coap_new_pdu(transport, dlen); + coap_pdu_t *pdu = coap_new_pdu2(transport, dlen); if (!pdu) { OIC_LOG(ERROR, TAG, "outpdu is null"); + OIC_LOG_V(ERROR, TAG, "data length: %zu", dlen); return 0; } - int ret = coap_pdu_parse((unsigned char *) data, dlen, pdu, transport); + int ret = coap_pdu_parse2((unsigned char *) data, dlen, pdu, transport); if (0 >= ret) { OIC_LOG(ERROR, TAG, "pdu parse failed"); @@ -980,73 +1337,70 @@ static size_t CACheckPayloadLength(const void *data, size_t dlen) return payloadLen; } -static void sendData(const CAEndpoint_t *endpoint, const void *data, - size_t dlen, const char *fam) +static ssize_t sendData(const CAEndpoint_t *endpoint, const void *data, + size_t dlen, const char *fam) { - // #1. get TCP Server object from list - size_t index = 0; - CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index); - if (!svritem) - { - // if there is no connection info, connect to TCP Server - svritem = CAConnectTCPSession(endpoint); - if (!svritem) - { - OIC_LOG(ERROR, TAG, "Failed to create TCP server object"); - if (g_tcpErrorHandler) - { - g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED); - } - return; - } - } - - // #2. check payload length -#ifdef __WITH_TLS__ - if (false == CAIsTlsMessage(data, dlen)) -#endif - { - size_t payloadLen = CACheckPayloadLength(data, dlen); - // if payload length is zero, disconnect from TCP server - if (!payloadLen) - { - OIC_LOG(DEBUG, TAG, "payload length is zero, disconnect from remote device"); - CADisconnectTCPSession(svritem, index); - return; - } - } + OIC_LOG_V(INFO, TAG, "The length of data that needs to be sent is %zu bytes", dlen); - // #3. check connection state - if (svritem->fd < 0) + // #1. find a session info from list. + CASocketFd_t sockFd = CAGetSocketFDFromEndpoint(endpoint); + if (OC_INVALID_SOCKET == sockFd) { - // if file descriptor value is wrong, remove TCP Server info from list - OIC_LOG(ERROR, TAG, "Failed to connect to TCP server"); - CADisconnectTCPSession(svritem, index); - if (g_tcpErrorHandler) + // if there is no connection info, connect to remote device. + sockFd = CAConnectTCPSession(endpoint); + if (OC_INVALID_SOCKET == sockFd) { - g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED); + OIC_LOG(ERROR, TAG, "Failed to create tcp session object"); + return -1; } - return; } - // #4. send data to TCP Server + // #2. send data to remote device. ssize_t remainLen = dlen; + unsigned int sendRetryTime = 1; do { - ssize_t len = send(svritem->fd, data, remainLen, 0); +#ifdef MSG_NOSIGNAL + ssize_t len = send(sockFd, data, remainLen, MSG_DONTWAIT | MSG_NOSIGNAL); +#else + ssize_t len = send(sockFd, data, remainLen, MSG_DONTWAIT); +#endif if (-1 == len) { - if (EWOULDBLOCK != errno) + if (EWOULDBLOCK != errno && EAGAIN != errno) { OIC_LOG_V(ERROR, TAG, "unicast ipv4tcp sendTo failed: %s", strerror(errno)); - if (g_tcpErrorHandler) - { - g_tcpErrorHandler(endpoint, data, dlen, CA_SEND_FAILED); - } - return; + CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port, + len, false, strerror(errno)); + return len; + } + + // re-trying send after 10, 20, 40, 80, 160 and 320 milliseconds + if (sendRetryTime > 32) + { + return len; } + + unsigned int waitTime = sendRetryTime * 10 * MILLISECONDS_PER_SECOND; + OIC_LOG_V(WARNING, TAG, "send blocked. trying send after %u microseconds", waitTime); + + oc_mutex_lock(g_mutexSend); + oc_cond_wait_for(g_condSend, g_mutexSend, waitTime); + oc_mutex_unlock(g_mutexSend); + + oc_mutex_lock(g_mutexObjectList); + if (caglobals.tcp.terminate) + { + oc_mutex_unlock(g_mutexObjectList); + return len; + } + oc_mutex_unlock(g_mutexObjectList); + + sendRetryTime = (sendRetryTime << 1); + continue; } + sendRetryTime = 1; data += len; remainLen -= len; } while (remainLen > 0); @@ -1055,25 +1409,27 @@ static void sendData(const CAEndpoint_t *endpoint, const void *data, (void)fam; #endif OIC_LOG_V(INFO, TAG, "unicast %stcp sendTo is successful: %zu bytes", fam, dlen); + CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port, + dlen, true, NULL); + return dlen; } -void CATCPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen, - bool isMulticast) +ssize_t CATCPSendData(CAEndpoint_t *endpoint, const void *data, size_t datalen) { - VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL"); - VERIFY_NON_NULL_VOID(data, TAG, "data is NULL"); + VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", -1); + VERIFY_NON_NULL_RET(data, TAG, "data is NULL", -1); - if (!isMulticast) + if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6)) { - if (caglobals.tcp.ipv6tcpenabled && (endpoint->flags & CA_IPV6)) - { - sendData(endpoint, data, datalen, "ipv6"); - } - if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4)) - { - sendData(endpoint, data, datalen, "ipv4"); - } + return sendData(endpoint, data, datalen, "ipv6"); } + if (caglobals.tcp.ipv4tcpenabled && (endpoint->flags & CA_IPV4)) + { + return sendData(endpoint, data, datalen, "ipv4"); + } + + OIC_LOG(ERROR, TAG, "Not supported transport flags"); + return -1; } CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size) @@ -1084,35 +1440,36 @@ CAResult_t CAGetTCPInterfaceInformation(CAEndpoint_t **info, uint32_t *size) return CA_NOT_SUPPORTED; } -CATCPSessionInfo_t *CAConnectTCPSession(const CAEndpoint_t *endpoint) +CASocketFd_t CAConnectTCPSession(const CAEndpoint_t *endpoint) { - VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL); + VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET); // #1. create TCP server object CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) OICCalloc(1, sizeof (*svritem)); if (!svritem) { OIC_LOG(ERROR, TAG, "Out of memory"); - return NULL; + return OC_INVALID_SOCKET; } memcpy(svritem->sep.endpoint.addr, endpoint->addr, sizeof(svritem->sep.endpoint.addr)); svritem->sep.endpoint.adapter = endpoint->adapter; svritem->sep.endpoint.port = endpoint->port; svritem->sep.endpoint.flags = endpoint->flags; svritem->sep.endpoint.ifindex = endpoint->ifindex; + svritem->state = CONNECTING; + svritem->isClient = true; - // #2. create the socket and connect to TCP server - int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET; - int fd = CATCPCreateSocket(family, svritem); - if (-1 == fd) + // Allocate message buffer + svritem->tlsdata = (unsigned char*) OICCalloc(TLS_DATA_MAX_SIZE, sizeof(unsigned char)); + if (!svritem->tlsdata) { + OIC_LOG(ERROR, TAG, "Out of memory"); OICFree(svritem); - return NULL; + return OC_INVALID_SOCKET; } - // #3. add TCP connection info to list - svritem->fd = fd; - ca_mutex_lock(g_mutexObjectList); + // #2. add TCP connection info to list + oc_mutex_lock(g_mutexObjectList); if (caglobals.tcp.svrlist) { bool res = u_arraylist_add(caglobals.tcp.svrlist, svritem); @@ -1120,71 +1477,98 @@ CATCPSessionInfo_t *CAConnectTCPSession(const CAEndpoint_t *endpoint) { OIC_LOG(ERROR, TAG, "u_arraylist_add failed."); close(svritem->fd); + OICFree(svritem->tlsdata); OICFree(svritem); - ca_mutex_unlock(g_mutexObjectList); - return NULL; + oc_mutex_unlock(g_mutexObjectList); + return OC_INVALID_SOCKET; } } - ca_mutex_unlock(g_mutexObjectList); + oc_mutex_unlock(g_mutexObjectList); - CHECKFD(fd); + // #3. create the socket and connect to TCP server + int family = (svritem->sep.endpoint.flags & CA_IPV6) ? AF_INET6 : AF_INET; + if (CA_STATUS_OK != CATCPCreateSocket(family, svritem)) + { + return OC_INVALID_SOCKET; + } - // pass the connection information to CA Common Layer. + // #4. pass the connection information to CA Common Layer. if (g_connectionCallback) { - g_connectionCallback(&(svritem->sep.endpoint), true); + g_connectionCallback(&(svritem->sep.endpoint), true, svritem->isClient); } - return svritem; + return svritem->fd; } -CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *svritem, size_t index) +CAResult_t CADisconnectTCPSession(size_t index) { - VERIFY_NON_NULL(svritem, TAG, "svritem is NULL"); - - ca_mutex_lock(g_mutexObjectList); - - // close the socket and remove TCP connection info in list - if (svritem->fd >= 0) + CATCPSessionInfo_t *removedData = u_arraylist_remove(caglobals.tcp.svrlist, index); + if (!removedData) { - close(svritem->fd); + OIC_LOG(DEBUG, TAG, "there is no data to be removed"); + return CA_STATUS_OK; } - u_arraylist_remove(caglobals.tcp.svrlist, index); - OICFree(svritem->data); - svritem->data = NULL; - // pass the connection information to CA Common Layer. - if (g_connectionCallback) + // close the socket and remove session info in list. + if (removedData->fd >= 0) { - g_connectionCallback(&(svritem->sep.endpoint), false); + shutdown(removedData->fd, SHUT_RDWR); + close(removedData->fd); + removedData->fd = -1; + removedData->state = (CONNECTED == removedData->state) ? + DISCONNECTED : removedData->state; + + // pass the connection information to CA Common Layer. + if (g_connectionCallback && DISCONNECTED == removedData->state) + { + g_connectionCallback(&(removedData->sep.endpoint), false, removedData->isClient); + } } + OICFree(removedData->data); + removedData->data = NULL; + + OICFree(removedData->tlsdata); + removedData->tlsdata = NULL; + + OICFree(removedData); + removedData = NULL; - OICFree(svritem); - ca_mutex_unlock(g_mutexObjectList); + OIC_LOG(DEBUG, TAG, "data is removed from session list"); + +#ifndef DISABLE_TCP_SERVER + if (caglobals.server && MAX_CONNECTION_COUNTS == u_arraylist_length(caglobals.tcp.svrlist) + 1) + { + CATCPInitializeSocket(); + } +#endif return CA_STATUS_OK; } void CATCPDisconnectAll() { - ca_mutex_lock(g_mutexObjectList); - uint32_t length = u_arraylist_length(caglobals.tcp.svrlist); + OIC_LOG(DEBUG, TAG, "IN - CATCPDisconnectAll"); - CATCPSessionInfo_t *svritem = NULL; - for (size_t i = 0; i < length; i++) - { - svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i); - if (svritem && svritem->fd >= 0) - { - shutdown(svritem->fd, SHUT_RDWR); - close(svritem->fd); + oc_mutex_lock(g_mutexObjectList); - OICFree(svritem->data); - svritem->data = NULL; - } + uint32_t length = u_arraylist_length(caglobals.tcp.svrlist); + for (ssize_t index = length; index > 0; index--) + { + // disconnect session from remote device. + CADisconnectTCPSession(index - 1); } + u_arraylist_destroy(caglobals.tcp.svrlist); - ca_mutex_unlock(g_mutexObjectList); + caglobals.tcp.svrlist = NULL; + + oc_mutex_unlock(g_mutexObjectList); + +#ifdef __WITH_TLS__ + CAcloseSslConnectionAll(CA_ADAPTER_TCP); +#endif + + OIC_LOG(DEBUG, TAG, "OUT - CATCPDisconnectAll"); } CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint, size_t *index) @@ -1192,6 +1576,8 @@ CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", NULL); VERIFY_NON_NULL_RET(index, TAG, "index is NULL", NULL); + OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port); + // get connection info from list uint32_t length = u_arraylist_length(caglobals.tcp.svrlist); for (size_t i = 0; i < length; i++) @@ -1208,17 +1594,52 @@ CATCPSessionInfo_t *CAGetTCPSessionInfoFromEndpoint(const CAEndpoint_t *endpoint && (svritem->sep.endpoint.port == endpoint->port) && (svritem->sep.endpoint.flags & endpoint->flags)) { + OIC_LOG(DEBUG, TAG, "Found in session list"); *index = i; return svritem; } } + OIC_LOG(DEBUG, TAG, "Session not found"); return NULL; } +CASocketFd_t CAGetSocketFDFromEndpoint(const CAEndpoint_t *endpoint) +{ + VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint is NULL", OC_INVALID_SOCKET); + + OIC_LOG_V(DEBUG, TAG, "Looking for [%s:%d]", endpoint->addr, endpoint->port); + + // get connection info from list. + oc_mutex_lock(g_mutexObjectList); + uint32_t length = u_arraylist_length(caglobals.tcp.svrlist); + for (size_t i = 0; i < length; i++) + { + CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get( + caglobals.tcp.svrlist, i); + if (!svritem) + { + continue; + } + + if (!strncmp(svritem->sep.endpoint.addr, endpoint->addr, + sizeof(svritem->sep.endpoint.addr)) + && (svritem->sep.endpoint.port == endpoint->port) + && (svritem->sep.endpoint.flags & endpoint->flags)) + { + oc_mutex_unlock(g_mutexObjectList); + OIC_LOG(DEBUG, TAG, "Found in session list"); + return svritem->fd; + } + } + + oc_mutex_unlock(g_mutexObjectList); + OIC_LOG(DEBUG, TAG, "Session not found"); + return OC_INVALID_SOCKET; +} + CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index) { - ca_mutex_lock(g_mutexObjectList); // check from the last item. CATCPSessionInfo_t *svritem = NULL; @@ -1230,21 +1651,89 @@ CATCPSessionInfo_t *CAGetSessionInfoFromFD(int fd, size_t *index) if (svritem && svritem->fd == fd) { *index = i; - ca_mutex_unlock(g_mutexObjectList); + oc_mutex_unlock(g_mutexObjectList); return svritem; } } - ca_mutex_unlock(g_mutexObjectList); return NULL; } +static CATCPSessionInfo_t *CAGetSessionInfoFromFDAsOwner(int fd, size_t *index) +{ + CATCPSessionInfo_t *svritem = NULL; + uint32_t length = u_arraylist_length(caglobals.tcp.svrlist); + for (size_t i = 0; i < length; i++) + { + svritem = (CATCPSessionInfo_t *) u_arraylist_get(caglobals.tcp.svrlist, i); + + if (svritem && svritem->fd == fd) + { + *index = i; + return svritem; + } + } + + return NULL; +} + +CAResult_t CASearchAndDeleteTCPSession(const CAEndpoint_t *endpoint) +{ + oc_mutex_lock(g_mutexObjectList); + + CAResult_t result = CA_STATUS_OK; + size_t index = 0; + CATCPSessionInfo_t *svritem = CAGetTCPSessionInfoFromEndpoint(endpoint, &index); + if (svritem) + { + result = CADisconnectTCPSession(index); + if (CA_STATUS_OK != result) + { + OIC_LOG_V(ERROR, TAG, "CADisconnectTCPSession failed, result[%d]", result); + } + } + + oc_mutex_unlock(g_mutexObjectList); + return result; +} + +void CATCPCloseInProgressConnections() +{ + OIC_LOG(INFO, TAG, "IN - CATCPCloseInProgressConnections"); + + oc_mutex_lock(g_mutexObjectList); + + uint32_t length = u_arraylist_length(caglobals.tcp.svrlist); + for (size_t index = 0; index < length; index++) + { + CATCPSessionInfo_t *svritem = (CATCPSessionInfo_t *) u_arraylist_get( + caglobals.tcp.svrlist, index); + if (!svritem) + { + continue; + } + + // Session which are connecting state + if (svritem->fd >= 0 && svritem->state == CONNECTING) + { + shutdown(svritem->fd, SHUT_RDWR); + close(svritem->fd); + svritem->fd = -1; + svritem->state = DISCONNECTED; + } + } + + oc_mutex_unlock(g_mutexObjectList); + + OIC_LOG(INFO, TAG, "OUT - CATCPCloseInProgressConnections"); +} + size_t CAGetTotalLengthFromHeader(const unsigned char *recvBuffer) { OIC_LOG(DEBUG, TAG, "IN - CAGetTotalLengthFromHeader"); - coap_transport_type transport = coap_get_tcp_header_type_from_initbyte( + coap_transport_t transport = coap_get_tcp_header_type_from_initbyte( ((unsigned char *)recvBuffer)[0] >> 4); size_t optPaylaodLen = coap_get_length_from_header((unsigned char *)recvBuffer, transport);