int32_t Plaintext_Recv()

in platform/posix/transport/src/plaintext_posix.c [113:175]


int32_t Plaintext_Recv( NetworkContext_t * pNetworkContext,
                        void * pBuffer,
                        size_t bytesToRecv )
{
    PlaintextParams_t * pPlaintextParams = NULL;
    int32_t bytesReceived = -1, pollStatus = 1;
    struct pollfd pollFds;

    assert( pNetworkContext != NULL && pNetworkContext->pParams != NULL );
    assert( pBuffer != NULL );
    assert( bytesToRecv > 0 );

    /* Get receive timeout from the socket to use as the timeout for #select. */
    pPlaintextParams = pNetworkContext->pParams;

    /* Initialize the file descriptor.
     * #POLLPRI corresponds to high-priority data while #POLLIN corresponds
     * to any other data that may be read. */
    pollFds.events = POLLIN | POLLPRI;
    pollFds.revents = 0;
    /* Set the file descriptor for poll. */
    pollFds.fd = pPlaintextParams->socketDescriptor;

    /* Check if there is data to read (without blocking) from the socket. */
    pollStatus = poll( &pollFds, 1, 0 );

    if( pollStatus > 0 )
    {
        /* The socket is available for receiving data. */
        bytesReceived = ( int32_t ) recv( pPlaintextParams->socketDescriptor,
                                          pBuffer,
                                          bytesToRecv,
                                          0 );
    }
    else if( pollStatus < 0 )
    {
        /* An error occurred while polling. */
        bytesReceived = -1;
    }
    else
    {
        /* No data available to receive. */
        bytesReceived = 0;
    }

    /* Note: A zero value return from recv() represents
     * closure of TCP connection by the peer. */
    if( ( pollStatus > 0 ) && ( bytesReceived == 0 ) )
    {
        /* Peer has closed the connection. Treat as an error. */
        bytesReceived = -1;
    }
    else if( bytesReceived < 0 )
    {
        logTransportError( errno );
    }
    else
    {
        /* Empty else MISRA 15.7 */
    }

    return bytesReceived;
}