/* 
  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_freeaddrinfo.c
*
* \author Thorsten Alteholz <libcontra@alteholz.eu>
*
* \brief wrapper for freeaddinfo()
*
* free addrinfo structures
* man 2 freeaddrinfo
*
*
* \addtogroup libcontra
* The group of the library.
* @{
************************************************************************/

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

extern bool	libcontra_logFreeaddrinfo; /*!< 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 void freeaddrinfo(struct addrinfo *ai)
*
* \author Thorsten Alteholz <libcontra@alteholz.eu>
*
* \brief wrapper around libc::freeaddrinfo()
* 
* @param[in]   ai        pointer to addrinfo struct that shall be freed
*
* \return void function
*
************************************************************************/
void freeaddrinfo(struct addrinfo *ai)
{
  int (*libc_freeaddrinfo)(struct addrinfo *ai);
  int rc;

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

  if (libcontra_logFreeaddrinfo) {
    libcontra_log(LOGLEVEL_DEBUG, "D: freeaddrinfo start");
    libcontra_log(LOGLEVEL_INFO, "I: free addressinfo of %s\n",ai->ai_canonname);
  }

  *(void **)(&libc_freeaddrinfo) = dlsym(RTLD_NEXT, "freeaddrinfo");
  if(dlerror()) {
    errno = EACCES;
    return;
  }

  (*libc_freeaddrinfo)(ai);
  
  if (libcontra_logFreeaddrinfo) {
    libcontra_log(LOGLEVEL_DEBUG, "D: freeaddrinfo end");
  }

  return;
}

/*! @} */

