+ 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