+ 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 // Non-Secure connection
+ {
+ svritem->protocol = COAP;
+
+ // 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)
+ {
+ 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);
+ }
+ }