+ 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 = %u", tlsLength);
+ if (tlsLength > sizeof(svritem->tlsdata))
+ {
+ OIC_LOG_V(ERROR, TAG, "total tls length is too big (buffer size : %u)",
+ sizeof(svritem->tlsdata));
+ if (CA_STATUS_OK != CAcloseSslConnection(&svritem->sep.endpoint))
+ {
+ OIC_LOG(ERROR, TAG, "Failed to close TLS session");
+ }
+ CASearchAndDeleteTCPSession(&(svritem->sep.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 : %u bytes , recv() : %d bytes, svritem->tlsLen : %u bytes",
+ nbRead, len, svritem->tlsLen);
+ if (tlsLength > 0 && tlsLength == svritem->tlsLen)
+ {
+ //when successfully read data - pass them to callback.
+ res = CAdecryptSsl(&svritem->sep, (uint8_t *)svritem->tlsdata, svritem->tlsLen);
+ svritem->tlsLen = 0;
+ OIC_LOG_V(INFO, TAG, "%s: CAdecryptSsl returned %d", __func__, res);
+ }
+ }
+#endif
+