/* 
  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_accept.c
*
* \author Thorsten Alteholz <libcontra@alteholz.eu>
*
* \brief wrapper for accept()
*
* accept a connection on a socket
* man 2 accept 
*
*
* \addtogroup libcontra
* The group of the library.
* @{
************************************************************************/

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

extern bool	libcontra_logAccept; /*!< 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 int accept(int socket, struct sockaddr *restrict address,socklen_t *restrict address_len)
*
* \author Thorsten Alteholz <libcontra@alteholz.eu>
*
* \brief wrapper around libc::accept()
* 
* @param[in]   socket        socket created by socket(2)
* @param[in]   *address      a pointer to a sockaddr structure that is filled
*                            in with the address of the peer socket
* @param[in]   *address_len  size (in bytes) ot the structure pointed to by addr
*
* \return On success, return a file descriptor for the accepted socket (>0).
*         On error, return -1, errno is set
*
************************************************************************/
int accept(int socket, struct sockaddr *restrict address, socklen_t *restrict address_len)
{
  int (*libc_accept)(int socket, struct sockaddr *restrict address,socklen_t *restrict address_len);
  int rc;

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

  if (libcontra_logAccept) {
    libcontra_log(LOGLEVEL_DEBUG, "D: accept start");
    libcontra_log(LOGLEVEL_INFO,  "I: accept socket v(%i)\n",socket);
  }

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

  rc = (*libc_accept)(socket, address, address_len);
  
  if (libcontra_logAccept) {
    libcontra_log(LOGLEVEL_INFO, "I: accept new socket: v(%i)", rc);
    libcontra_log(LOGLEVEL_DEBUG, "D: accept end");
  }

  return rc;
}

/*! @} */

