Esempio n. 1
0
/**
 * Read the CRT protocol header returning the length of the data field
 */
static int readHeader(int sd, void *buf)
{
	char *p = (char *) buf;

	int len;
	if ((len = recvBytes(sd, buf, CERT_HEADER_LEN)) <= 0)
		return len;

	if (p[0] != 'C' || p[1] != 'R' || p[2] != 'T') {
		logError("Bad MAGIC received in header\n");
		return -2;
	}
	if (p[3] != '0') {
		logError("Unknown protocol/request received in header\n");
		return -2;
	}
	certHeader_t *req = (certHeader_t *) buf;
	req->length = htonl(req->length);

	if (req->length == 0) {
		logWarn("Received header with data length = %d\n", req->length);
		return 0;
	}

	return req->length;
}
Esempio n. 2
0
void putFile(int sock, char * filename) {

    printf("Putting in file %s\n", filename);

    char recvbuf[1024];
    memset(recvbuf, 0, 1024);

    // create a file to write the contents into
    FILE * fp = fopen(filename, "w");
    if (fp == NULL) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }

    // continually read the bytes and write the data
    while(1) {

        ssize_t ret = 0;
        memset(recvbuf, 0, 1024);

        ret = recvBytes(sock, recvbuf, 1024);
        if (ret == 0) {
            // server closed connection, close the file
            fclose(fp);
            return;
        }
        fwrite(recvbuf, 1, ret, fp);
    }

}
Esempio n. 3
0
/**
 * Method to validate the password sent to server from the client
 */
int checkPass(int sock) {

    char recvbuf[1024];
    memset(recvbuf, 0, 1024);

    recvBytes(sock, recvbuf, strlen(password));
    printf("Password received: %s\n", recvbuf);
    // check if it is equal to the password
    if(strcmp(recvbuf, password) == 0) {
        return 1;
    } else {
        return -1;
    }
}
Esempio n. 4
0
static TSS2_RC tctiRecvBytes( TSS2_TCTI_CONTEXT *tctiContext, SOCKET sock, unsigned char *data, int len )
{
    TSS2_RC result = 0;
    result = recvBytes( sock, data, len);
    if ( (INT32)result == SOCKET_ERROR) {
        TCTI_LOG( tctiContext, NO_PREFIX, "In recvBytes, recv failed (socket: 0x%x) with error: %d\n", sock, WSAGetLastError() );
        return TSS2_TCTI_RC_IO_ERROR;
    }
#ifdef DEBUG_SOCKETS
    TCTI_LOG( tctiContext, NO_PREFIX, "Receive Bytes from socket #0x%x: \n", sock );
    TCTI_LOG_BUFFER( tctiContext, NO_PREFIX, data, len );
#endif

    return TSS2_RC_SUCCESS;
}
Esempio n. 5
0
static int client()
{
	int sd = ipConnectPeer(arg.host, arg.port, 3);

	int filenameLen = strlen(arg.url);
	int reqLen = CERT_HEADER_LEN + filenameLen;
	certHeader_t *req = (certHeader_t *) malloc(reqLen);
	if (req == NULL)
		dieError("%s.malloc\n", __func__);

	req->id[0] = 'C';
	req->id[1] = 'R';
	req->id[2] = 'T';
	req->id[3] = '0';
	req->length = htonl(filenameLen);
	memcpy(&req->data[0], arg.url, filenameLen);
	logNorm("Requesting certificate '%s' (data len = %d)\n", arg.url, filenameLen);
	int len = ipsend(sd, req, reqLen);
	free(req);
	if (len < 0)
		return len;

	// Read the response
	char buf[1024];
	if ((len = readHeader(sd, buf)) < 0)
		return len;
	if (len == 0) {
		logError("Received error response (certificate not found?)\n");
		return -2;
	}

	void *certBuf = malloc(len);
	if (certBuf == NULL)
		dieError("%s.malloc\n", __func__);

	// Read the certificate
	int res;
	logNorm("Reading certificate of %d bytes\n", len);
	if ((res = recvBytes(sd, certBuf, len)) < 0)
		return res;
	hexdump(certBuf, 16, 16);

	close(sd);

	return 0;
}
Esempio n. 6
0
static int processRequest(int sd)
{
	char buf[1024];
	int len;

	if ((len = readHeader(sd, buf)) < 0)
		return len;
	if (len == 0) {
		logWarn("File not found, sending zero response\n", len);
		ipsend(sd, &idDefault, CERT_HEADER_LEN);
		return 0;
	}

	logNorm("Received header. Receiving data of length = %d\n", len);
	certHeader_t *req = (certHeader_t *) buf;
	if ((len = recvBytes(sd, &req->data, len)) <= 0)
		return len;

	char *filename = &req->data[0];
	filename[len] = 0;
	char *fileBuf;
	logNorm("Reading certificate file '%s'\n", filename);
	if ((len = readFile(filename, &fileBuf)) < 0)
		return len;

	int rspLen = CERT_HEADER_LEN + len;
	certHeader_t *rsp = (certHeader_t *) malloc(rspLen);
	if (rsp == NULL)
		dieError("%s.malloc\n", __func__);

	memcpy(&rsp->id, idDefault, 4);
	rsp->length = htonl(len);
	memcpy(&rsp->data, fileBuf, len);
	hexdump(&rsp->data, 16, 16);
	logNorm("Sending certificate of size %d bytes\n", len);
	len = ipsend(sd, rsp, rspLen);

	free(fileBuf);
	free(rsp);

	return len;
}
Esempio n. 7
0
/** Receive a raw string (not encoded by msgpack).
 * This IO call blocks.
 * We pass the lua_State to avoid mixing thread contexts.
 */
LuaStackSize lk::Socket::recv(lua_State *L) {
  if (lua_isnumber(L, 3)) {
    setRecvTimeout(lua_tonumber(L, 3));
  }

  if (lua_isnumber(L, 2)) {
    // <self> <num_bytes> [<timeout>]
    return recvBytes(L, lua_tonumber(L, 2));
  } else if (lua_isstring(L, 2)) {
    // <self> <mode> [<timeout>]
    const char *mode = lua_tostring(L, 2);
    if (mode[0] == '*' && mode[1] == 'a') {
      return recvAll(L);
    } else if (mode[0] == '*' && mode[1] == 'l') {
      return recvLine(L);
    } else {
      throw dub::Exception("Bad mode to recv (should be '*a' or '*l' but found '%s')", mode);
    }
  } 
  // receive a single line (not returning \r or \n).
  return recvLine(L);

  return 1;
}
Esempio n. 8
0
void receiveFile(int connfd) {
    char recvBuf[BUF_SIZE];
    int bytes;
    uint32_t fileSize, remaining, remainLastUpdate;
    char *fileName;
    FILE *file;
    time_t last, current, start;
    
    // Receive size
    bytes = 4;
    if (recvBytes(connfd, recvBuf, &bytes) != 0) exit(1);
    memcpy(&fileSize, recvBuf, 4);
    fileSize = ntohl(fileSize);
    
    // Receive name
    bytes = FNAME_LEN;
    if (recvBytes(connfd, recvBuf, &bytes) != 0) exit(1);
    fileName = malloc(strlen(recvBuf) + strlen(OUTPUT_DIR) + 2);
    // Prepend directory name
    strcpy(fileName, OUTPUT_DIR);
    strcat(fileName, "/");
    strcat(fileName, recvBuf);
    
    printf("ftps: Receiving file '%s' of size %u\n", fileName, fileSize);
    
    // Open file
    if ((file = fopen(fileName, "wb")) == NULL) {
        perror("ftps: Couldn't open file");
        exit(1);
    }
    
    // Receive and write file
    remainLastUpdate = remaining = fileSize;
    start = last = time(NULL);
    while (remaining > 0) {
        if ((bytes = RECV(connfd, recvBuf,
                          (remaining < BUF_SIZE) ? remaining : BUF_SIZE, 0)) == -1) {
            perror("ftps: recv");
            exit(1);
        }
        if (bytes == 0) {
            fprintf(stderr, "ftps: Connection lost.\n");
            exit(2);
        }
        remaining -= bytes;
        // Display info only once per second
        current = time(NULL);
        if (current >= last + 1) {
            printf("ftps: Received %.02f KB (%.02f KB/s)...\n",
                   (fileSize-remainLastUpdate)/1000.0,
                   ((remainLastUpdate-remaining)/1000.0)/difftime(current, last));
            last = current;
            remainLastUpdate = remaining;
        }
        // Write to file
        if (fwrite(recvBuf, 1, bytes, file) != bytes) {
            fprintf(stderr, "ftps: File write error!\n");
            exit(1);
        }
    }
    
    // Show stats
    current = time(NULL);
    printf("ftps: Received %.02f KB (average %.02f KB/s)...\n", fileSize/1000.0,
           (fileSize/1000.0)/difftime(current, start));
    
    fflush(file);
    fclose(file);
    printf("ftps: Done\n");
}
Esempio n. 9
0
TSS2_RC SocketReceiveTpmResponse(
    TSS2_TCTI_CONTEXT *tctiContext,     /* in */
    size_t          *response_size,     /* out */
    unsigned char   *response_buffer,    /* in */
    int32_t         timeout
    )
{
    UINT32 trash;
    size_t responseSize = 0;
    TSS2_RC rval = TSS2_RC_SUCCESS;
    fd_set readFds;
    struct timeval tv, *tvPtr;
    int32_t timeoutMsecs = timeout % 1000;
    int iResult;
    
    if( ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext )->status.debugMsgLevel == TSS2_TCTI_DEBUG_MSG_ENABLED )
    {
#ifdef DEBUG
        (*printfFunction)( rmDebugPrefix, "Response Received: " );
#endif
#ifdef DEBUG_SOCKETS
         (*printfFunction)( rmDebugPrefix, "from socket #0x%x:\n", TCTI_CONTEXT_INTEL->tpmSock );
#endif
    }

    if( *response_size > 0 )
    {
        if( timeout == TSS2_TCTI_TIMEOUT_BLOCK )
        {
            tvPtr = 0;
        }
        else
        {
            tv.tv_sec = timeout / 1000;
            tv.tv_usec = timeoutMsecs * 1000;
            tvPtr = &tv;
        }

        FD_ZERO( &readFds );
        FD_SET( TCTI_CONTEXT_INTEL->tpmSock, &readFds );

        iResult = select( TCTI_CONTEXT_INTEL->tpmSock+1, &readFds, 0, 0, tvPtr );
        if( iResult == 0 )
        {
            (*printfFunction)(NO_PREFIX, "select failed due to timeout, socket #: 0x%x\n", TCTI_CONTEXT_INTEL->tpmSock );
            rval = TSS2_TCTI_RC_TRY_AGAIN;
            goto retSocketReceiveTpmResponse;
        }
        else if( iResult == SOCKET_ERROR )
        {
            (*printfFunction)(NO_PREFIX, "select failed with socket error: %d\n", WSAGetLastError() );
            rval = TSS2_TCTI_RC_IO_ERROR;
            goto retSocketReceiveTpmResponse;
        }
        else if ( iResult != 1 )
        {
            (*printfFunction)(NO_PREFIX, "select failed, read the wrong # of bytes: %d\n", iResult );
            rval = TSS2_TCTI_RC_IO_ERROR;
            goto retSocketReceiveTpmResponse;
        }

        // Receive the size of the response.
        recvBytes( TCTI_CONTEXT_INTEL->tpmSock, (unsigned char *)&responseSize, 4 );
        
		responseSize = CHANGE_ENDIAN_DWORD( responseSize );
                
        // Receive the TPM response.
        recvBytes( TCTI_CONTEXT_INTEL->tpmSock, (unsigned char *)response_buffer, responseSize );

#ifdef DEBUG
        if( ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext )->status.debugMsgLevel == TSS2_TCTI_DEBUG_MSG_ENABLED )
        {
            DEBUG_PRINT_BUFFER( response_buffer, responseSize );
        }
#endif    

        // Receive the appended four bytes of 0's
        recvBytes( TCTI_CONTEXT_INTEL->tpmSock, (unsigned char *)&trash, 4 );
    }

    if( responseSize < *response_size )
    {
        *response_size = responseSize;
    }
    
    ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.commandSent = 0;

    // Turn cancel off.
    rval = (TSS2_RC)PlatformCommand( tctiContext, MS_SIM_CANCEL_OFF );

    if( ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext )->status.debugMsgLevel == TSS2_TCTI_DEBUG_MSG_ENABLED )
    {
//        (*printfFunction)(NO_PREFIX,  "%s sent cancel OFF command:\n", interfaceName );
    }

retSocketReceiveTpmResponse:
    return rval;
}
Esempio n. 10
0
void afLib::checkInterrupt(void) {
    int result;

    if (_interrupts_pending > 0) {
        //_theLog->print("_interrupts_pending: "); _theLog->println(_interrupts_pending);

        switch (_state) {
            case STATE_IDLE:
                if (_writeCmd != NULL) {
                    // Include 2 bytes for length
                    _bytesToSend = _writeCmd->getSize() + 2;
                } else {
                    _bytesToSend = 0;
                }
                _state = STATE_STATUS_SYNC;
                printState(_state);
                return;

            case STATE_STATUS_SYNC:
                _txStatus->setAck(false);
                _txStatus->setBytesToSend(_bytesToSend);
                _txStatus->setBytesToRecv(0);

                result = exchangeStatus(_txStatus, _rxStatus);

                if (result == 0 && _rxStatus->isValid() && inSync(_txStatus, _rxStatus)) {
                    _state = STATE_STATUS_ACK;
                    if (_txStatus->getBytesToSend() == 0 && _rxStatus->getBytesToRecv() > 0) {
                        _bytesToRecv = _rxStatus->getBytesToRecv();
                    }
                } else {
                    // Try resending the preamble
                    _state = STATE_STATUS_SYNC;
                    _theLog->println("Collision");
//          _txStatus->dumpBytes();
//          _rxStatus->dumpBytes();
                }
                printState(_state);
                break;

            case STATE_STATUS_ACK:
                _txStatus->setAck(true);
                _txStatus->setBytesToRecv(_rxStatus->getBytesToRecv());
                _bytesToRecv = _rxStatus->getBytesToRecv();
                result = writeStatus(_txStatus);
                if (result != 0) {
                    _state = STATE_STATUS_SYNC;
                    printState(_state);
                    break;
                }
                if (_bytesToSend > 0) {
                    _writeBufferLen = (uint16_t) _writeCmd->getSize();
                    _writeBuffer = new uint8_t[_bytesToSend];
                    memcpy(_writeBuffer, (uint8_t * ) & _writeBufferLen, 2);
                    _writeCmd->getBytes(&_writeBuffer[2]);
                    _state = STATE_SEND_BYTES;
                } else if (_bytesToRecv > 0) {
                    _state = STATE_RECV_BYTES;
                } else {
                    _state = STATE_CMD_COMPLETE;
                }
                printState(_state);
                break;

            case STATE_SEND_BYTES:
//        _theLog->print("send bytes: "); _theLog->println(_bytesToSend);		
                sendBytes();

                if (_bytesToSend == 0) {
                    _writeBufferLen = 0;
                    delete (_writeBuffer);
                    _writeBuffer = NULL;
                    _state = STATE_CMD_COMPLETE;
                    printState(_state);
                }
                break;

            case STATE_RECV_BYTES:
//        _theLog->print("receive bytes: "); _theLog->println(_bytesToRecv);
                recvBytes();
                if (_bytesToRecv == 0) {
                    _state = STATE_CMD_COMPLETE;
                    printState(_state);
                    _readCmd = new Command(_theLog,_readBufferLen, &_readBuffer[2]);
                    delete (_readBuffer);
                    _readBuffer = NULL;
                }
                break;

            case STATE_CMD_COMPLETE:
                _state = STATE_IDLE;
                printState(_state);
                if (_readCmd != NULL) {
                    byte *val = new byte[_readCmd->getValueLen()];
                    _readCmd->getValue(val);

                    switch (_readCmd->getCommand()) {
                        case MSG_TYPE_SET:
                            _onAttrSet(_readCmd->getReqId(), _readCmd->getAttrId(), _readCmd->getValueLen(), val);
                            break;

                        case MSG_TYPE_UPDATE:
                            if (_readCmd->getAttrId() == _outstandingSetGetAttrId) {
                                _outstandingSetGetAttrId = 0;
                            }
                            _onAttrSetComplete(_readCmd->getReqId(), _readCmd->getAttrId(), _readCmd->getValueLen(), val);
                            break;

                        default:
                            break;
                    }
                    delete (val);
                    delete (_readCmd);
                    _readCmdOffset = 0;
                    _readCmd = NULL;
                }

                if (_writeCmd != NULL) {
                    // Fake a callback here for MCU attributes as we don't get one from the module.
                    if (_writeCmd->getCommand() == MSG_TYPE_UPDATE && IS_MCU_ATTR(_writeCmd->getAttrId())) {
                        _onAttrSetComplete(_writeCmd->getReqId(), _writeCmd->getAttrId(), _writeCmd->getValueLen(), _writeCmd->getValueP());
                    }
                    delete (_writeCmd);
                    _writeCmdOffset = 0;
                    _writeCmd = NULL;
                }
                break;
        }

        updateIntsPending(-1);
    }
}
Esempio n. 11
0
int main(int argc, char* argv[])
{

        // args should only be the port number and the name
        // of the program running
        if (argc != 2) {
            printf("Usage Error - provide port number\n");
            exit(1);
        }

	char *port = argv[1];

        // create the ./files dir
        createSubdir();


	// getaddrinfo(): network address and service translation:
	struct addrinfo *socketaddrinfo = example_getaddrinfo(NULL, port);

	// socket(): create an endpoint for communication
	int sock = example_socket(socketaddrinfo);

	example_setsockopt(sock);
	example_bind(sock, socketaddrinfo);
	example_listen(sock, 128);
	freeaddrinfo(socketaddrinfo); // done with socketaddrinfo

	//printf("Press Ctrl+C to exit server.\n");
	//printf("Run a web browser on the same computer as you run the server and point it to:\n");
	//printf("http://127.0.0.1:%s\n", port);

	while(1)
	{
                printf("Waiting for connections...\n");
		// Get a socket for a particular incoming connection.
		int newsock = accept(sock, NULL, NULL);
		if(newsock == -1)
		{
			perror("accept(): ");
			continue; // try again if accept failed.
		}
                printf("Client connected\n");

                // Check the password of the client
                if (checkPass(newsock) == -1) {
                    printf("Incorrect password - Connection aborted\n");
                    closeSock(newsock);
                    continue;
                } else {
                    printf("Password accepted - Continuing connection\n");
                }

	        sendBytes(newsock, "You connected!\n", strlen("You connected!\n"));

                char cmd[1024];
                memset(cmd, 0, 1024);
                recvBytes(newsock, cmd, 1024);

                printf("Received command: %s\n", cmd);

                if (strcmp(cmd, "list") == 0) {
                    sendBytes(newsock, "File listing:\n", strlen("File listing:\n"));

                    // Scan the dirextory and send the file list
                    sendList(newsock);
                    continue;
                }

                if (strcmp(cmd, "get") == 0) {
                    char retBuf[1024];
                    memset(retBuf, 0, 1024);

                    // Read the name of the file
                    recvBytes(newsock, retBuf, 1024);

                    // Check if the file exists and send it
                    getFile(newsock, retBuf);
                    continue;
                }

                if (strcmp(cmd, "put") == 0) {
                    char retBuf[1024];
                    memset(retBuf, 0, 1024);

                    // Read the name of the file
                    getLine(newsock, retBuf);

                    // Check if the file exists and send it
                    putFile(newsock, retBuf);
                    continue;
                }

//		char http_body[] = "hello world";
//		char http_headers[1024];
//		snprintf(http_headers, 1024,
//		         "HTTP/1.0 200 OK\r\n"
//		         "Content-Length: %zu\r\n"
//		         "Content-Type: text/html\r\n\r\n",
//		         strlen(http_body)); // should check return value


		/* Note: send() does not guarantee that it will send all of
		 * the data that we ask it too. To reliably send data, we
		 * should inspect the return value from send() and then call
		 * send() again on any bytes did not get sent. */

		// Send the HTTP headers
		//if(send(newsock, http_headers, strlen(http_headers), 0) == -1)
		//{
		//	perror("send");
		//	close(newsock);
		//	exit(EXIT_FAILURE);
		//}

		//// Send the HTTP body
		//if(send(newsock, http_body, strlen(http_body), 0) == -1)
		//{
		//	perror("send");
		//	close(newsock);
		//	exit(EXIT_FAILURE);
		//}

		/* shutdown() (see "man 2 shutdown") can be used before
		   close(). It allows you to partially close a socket (i.e.,
		   indicate that we are done sending data but still could
		   receive). This could allow us to signal to a peer that we
		   are done sending data while still allowing us to receive
		   data. SHUT_RD will disallow reads from the socket, SHUT_WR
		   will disallow writes, and SHUT_RDWR will disallow read and
		   write. Also, unlike close(), shutdown() will affect all
		   processes that are sharing the socket---while close() only
		   affects the process that calls it. */
#if 0
		if(shutdown(newsock, SHUT_RDWR) == -1)
		{
			perror("shutdown");
			close(newsock);
			exit(EXIT_FAILURE);
		}
#endif

		closeSock(newsock);
	}
}
Esempio n. 12
0
TSS2_RC SocketReceiveTpmResponse(
    TSS2_TCTI_CONTEXT *tctiContext,     /* in */
    size_t          *response_size,     /* out */
    unsigned char   *response_buffer,    /* in */
    int32_t         timeout
    )
{
    UINT32 trash;
    TSS2_RC rval = TSS2_RC_SUCCESS;
    fd_set readFds;
    struct timeval tv, *tvPtr;
    int32_t timeoutMsecs = timeout % 1000;
    int iResult;
    unsigned char responseSizeDelta = 0;

    rval = CommonReceiveChecks( tctiContext, response_size, response_buffer );
    if( rval != TSS2_RC_SUCCESS )
    {
        goto retSocketReceiveTpmResponse;
    }        
    
    if( timeout == TSS2_TCTI_TIMEOUT_BLOCK )
    {
        tvPtr = 0;
    }
    else
    {
        tv.tv_sec = timeout / 1000;
        tv.tv_usec = timeoutMsecs * 1000;
        tvPtr = &tv;
    }

    FD_ZERO( &readFds );
    FD_SET( TCTI_CONTEXT_INTEL->tpmSock, &readFds );

    iResult = select( TCTI_CONTEXT_INTEL->tpmSock+1, &readFds, 0, 0, tvPtr );
    if( iResult == 0 )
    {
        (*printfFunction)(NO_PREFIX, "select failed due to timeout, socket #: 0x%x\n", TCTI_CONTEXT_INTEL->tpmSock );
        rval = TSS2_TCTI_RC_TRY_AGAIN;
        goto retSocketReceiveTpmResponse;
    }
    else if( iResult == SOCKET_ERROR )
    {
        (*printfFunction)(NO_PREFIX, "select failed with socket error: %d\n", WSAGetLastError() );
        rval = TSS2_TCTI_RC_IO_ERROR;
        goto retSocketReceiveTpmResponse;
    }
    else if ( iResult != 1 )
    {
        (*printfFunction)(NO_PREFIX, "select failed, read the wrong # of bytes: %d\n", iResult );
        rval = TSS2_TCTI_RC_IO_ERROR;
        goto retSocketReceiveTpmResponse;
    }

    if( ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.protocolResponseSizeReceived != 1 )
    {        
        // Receive the size of the response.
        rval = recvBytes( TCTI_CONTEXT_INTEL->tpmSock, (unsigned char *)& (((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->responseSize ), 4 );
        if( rval != TSS2_RC_SUCCESS )
            goto retSocketReceiveTpmResponse;

        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->responseSize = CHANGE_ENDIAN_DWORD( ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->responseSize );
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.protocolResponseSizeReceived = 1;
    }

    if( response_buffer == NULL )
    {
        // In this case, just return the size
        *response_size = ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->responseSize;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.protocolResponseSizeReceived = 1;
        goto retSocketReceiveTpmResponse;
    }

    if( *response_size < ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->responseSize )
    {
        *response_size = ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->responseSize;
        rval = TSS2_TCTI_RC_INSUFFICIENT_BUFFER; 


        // If possible, receive tag from TPM.
        if( *response_size >= sizeof( TPM_ST ) && ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.tagReceived == 0 )
        {
            if( TSS2_RC_SUCCESS != recvBytes( TCTI_CONTEXT_INTEL->tpmSock, (unsigned char *)&( ( (TSS2_TCTI_CONTEXT_INTEL *)tctiContext )->tag ), 2 ) )
            {
                goto retSocketReceiveTpmResponse;
            }
            else
            {
                ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.tagReceived = 1;
            }
        }

        // If possible, receive response size from TPM
        if( *response_size >= ( sizeof( TPM_ST ) + sizeof( TPM_RC ) ) && ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.responseSizeReceived == 0 )
        {
            if( TSS2_RC_SUCCESS != recvBytes( TCTI_CONTEXT_INTEL->tpmSock, (unsigned char *)&( ( (TSS2_TCTI_CONTEXT_INTEL *)tctiContext )->responseSize ), 4 ) )
            {
                goto retSocketReceiveTpmResponse;
            }
            else
            {
                ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->responseSize = CHANGE_ENDIAN_DWORD( ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->responseSize );
                ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.responseSizeReceived = 1;
            }
        }
    }
    else
    {
        if( ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext )->status.debugMsgLevel == TSS2_TCTI_DEBUG_MSG_ENABLED &&
                ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->responseSize > 0 )
        {
#ifdef DEBUG
            (*printfFunction)( rmDebugPrefix, "Response Received: " );
#endif
#ifdef DEBUG_SOCKETS
            (*printfFunction)( rmDebugPrefix, "from socket #0x%x:\n", TCTI_CONTEXT_INTEL->tpmSock );
#endif
        }
        
        if( ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.tagReceived == 1 )
        {
            *(TPM_ST *)response_buffer = ( (TSS2_TCTI_CONTEXT_INTEL *)tctiContext )->tag;
            responseSizeDelta += sizeof( TPM_ST );
            response_buffer += sizeof( TPM_ST );
        }

        if( ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.responseSizeReceived == 1 )
        {
            *(TPM_RC *)response_buffer = CHANGE_ENDIAN_DWORD( ( (TSS2_TCTI_CONTEXT_INTEL *)tctiContext )->responseSize );
            responseSizeDelta += sizeof( TPM_RC );
            response_buffer += sizeof( TPM_RC );
        }

        // Receive the TPM response.
        rval = recvBytes( TCTI_CONTEXT_INTEL->tpmSock, (unsigned char *)response_buffer, ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->responseSize - responseSizeDelta );
        if( rval != TSS2_RC_SUCCESS )
            goto retSocketReceiveTpmResponse;

#ifdef DEBUG
        if( ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext )->status.debugMsgLevel == TSS2_TCTI_DEBUG_MSG_ENABLED )
        {
            DEBUG_PRINT_BUFFER( response_buffer, ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->responseSize );
        }
#endif

        // Receive the appended four bytes of 0's
        rval = recvBytes( TCTI_CONTEXT_INTEL->tpmSock, (unsigned char *)&trash, 4 );
        if( rval != TSS2_RC_SUCCESS )
            goto retSocketReceiveTpmResponse;
    }

    if( ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->responseSize < *response_size )
    {
        *response_size = ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->responseSize;
    }
    
    ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.commandSent = 0;

    // Turn cancel off.
    if( rval == TSS2_RC_SUCCESS )
    {
        rval = (TSS2_RC)PlatformCommand( tctiContext, MS_SIM_CANCEL_OFF );
    }
    else
    {
        // Ignore return value so earlier error code is preserved.
        PlatformCommand( tctiContext, MS_SIM_CANCEL_OFF );
    }

    if( ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext )->status.debugMsgLevel == TSS2_TCTI_DEBUG_MSG_ENABLED )
    {
//        (*printfFunction)(NO_PREFIX,  "%s sent cancel OFF command:\n", interfaceName );
    }

retSocketReceiveTpmResponse:
    if( rval == TSS2_RC_SUCCESS && 
		response_buffer != NULL )
    {
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->previousStage = TCTI_STAGE_RECEIVE_RESPONSE;
    }
    
    return rval;
}