/* 
  Copyright 2018-2023 Thorsten Alteholz <libcontra@alteholz.eu>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; version 2 of the License

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program (see the file COPYING included with this
  distribution); if not, write to the Free Software Foundation, Inc.,
  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

/*!
*************************************************************************
*
* \file libcontra_recv.c
*
* \author Thorsten Alteholz <libcontra@alteholz.eu>
*
* \brief wrapper for recv()
*
* receive a message from a connected socket
* man 2 recv
*
*
* \addtogroup libcontra
* The group of the library.
* @{
************************************************************************/

#include <libcontra.h>
#include <libcontra_log.h>

extern bool	libcontra_logRecv; /*!< this is needed to control the output in the logging function */
extern bool	libcontra_isInitialized; /*!< this is needed to control the output in the logging function */

/*!
*************************************************************************
*
* \fn ssize_t recv(int socket, void *buffer, size_t length, int flags)
*
* \author Thorsten Alteholz <libcontra@alteholz.eu>
*
* \brief wrapper around libc::recv()
* 
* @param[in]  socket  socket to receive message on
* @param[out] buffer  buffer containing message
* @param[in]  length  length of available buffer
* @param[in]  flags   type of message reception
*
* \return On success, a positive value indicates the length of the message
*                     0 no message available
*         On error, return -1, errno is set
*
************************************************************************/
ssize_t recv(int socket, void *buffer, size_t length, int flags)
{
  int (*libc_recv)(int socket, const void *buffer, size_t length, int flags);
  int rc;

  if (libcontra_isInitialized==false) {
    libcontra_init();
  } 

  if (libcontra_logRecv) {
    libcontra_log(LOGLEVEL_DEBUG, "D: recv start");
    libcontra_log(LOGLEVEL_INFO,  "I: recv from socket v(%i)", socket);
  }

  *(void **)(&libc_recv) = dlsym(RTLD_NEXT, "recv");
  if(dlerror()) {
    errno = EACCES;
    return -1;
  }

  rc = (*libc_recv)(socket, buffer, length, flags);
  
  if (libcontra_logRecv) {
    libcontra_log_data(LOGLEVEL_DEBUG, buffer, rc);
    libcontra_log(LOGLEVEL_INFO, "I: recv rc: %i", rc);
    libcontra_log(LOGLEVEL_DEBUG, "D: recv end");
  }

  return rc;
}

/*! @} */

