/* eurephiadb.c  --  Loads and initialises the database driver
 *
 *  GPLv2 only - Copyright (C) 2008 - 2012
 *               David Sommerseth <dazo@users.sourceforge.net>
 *
 *  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; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 */

/**
 * @file   eurephiadb.c
 * @author David Sommerseth <dazo@users.sourceforge.net>
 * @date   2008-08-06
 *
 * @brief  Handles loading and initialising of the database drivers
 *
 */

#include <stdio.h>
#include <dlfcn.h>

#include "eurephia_nullsafe.h"
#include "eurephiadb_driver.h"
#include "eurephia_log.h"
#include "eurephia_getsym.h"


/**
 * Unloads the database driver
 *
 * @param ctx eurephiaCTX
 *
 * @return Returns always 1.
 */
int eDBlink_close(eurephiaCTX *ctx)
{
        if( ctx == NULL ) {
                return 1;
        }

        eurephia_log(ctx, LOG_INFO, 3, "Unloading eurephia database driver");
        if( ctx->eurephia_driver != NULL ) {
                dlclose(ctx->eurephia_driver);
                ctx->eurephia_driver = NULL;
        }
        return 1;
}


/**
 * Loads and initialises the database driver.
 *
 * @param ctx      eurephiaCTX to which the database driver will be associated with
 * @param dbdriver Full path to the driver file (.so)
 * @param minver   The required minimum API level of the driver
 *
 * @return Returns 1 on success, otherwise 0.
 */
int eDBlink_init(eurephiaCTX *ctx, const char *dbdriver, const int minver)
{
        int apiver = -1;
        if( dbdriver == NULL ) {
                eurephia_log(ctx, LOG_FATAL, 0, "No eurephia database driver configured.  "
                             "eurephia authentication will not be available");
                return 0;
        }
        eurephia_log(ctx, LOG_INFO, 2, "Loading eurephia database driver: %s", dbdriver);

        ctx->eurephia_driver = dlopen(dbdriver, RTLD_NOW);
        if( ctx->eurephia_driver == NULL ) {
                eurephia_log(ctx, LOG_FATAL, 0, "Could not open the eurephia database driver (%s)", dbdriver);
                eurephia_log(ctx, LOG_FATAL, 1, "dlopen error: %s", dlerror());
                return 0;
        }

        // Find mandatory functions containing driver information
        eDB_DriverVersion = eGetSym(ctx, ctx->eurephia_driver, "eDB_DriverVersion");
        eDB_DriverAPIVersion = eGetSym(ctx, ctx->eurephia_driver, "eDB_DriverAPIVersion");

        eurephia_log(ctx, LOG_INFO, 1, "Driver loaded: %s (API version %i)",
                     eDB_DriverVersion(), eDB_DriverAPIVersion());

        // Check that we are using at least a new enough driver
        if( eDB_DriverAPIVersion() < minver ) {
                eurephia_log(ctx, LOG_FATAL, 0,
                             "The requested eurephia database driver is too old.  This program needs "
                             "API version %i, but this driver only supports API version %i.\n",
                             minver, eDB_DriverAPIVersion());
                return 0;
        }

        // Configure functions contained in the driver, defined by API version
        apiver = (eDB_DriverAPIVersion() > minver ? minver : eDB_DriverAPIVersion());
        switch( apiver ) {
        case -1:
                eurephia_log(ctx, LOG_FATAL, 0, "Something unexpected happened - apiver==-1");
                ctx->fatal_error = 1;
                break;

        default:
                eurephia_log(ctx, LOG_WARNING, 0,
                             "eurephia database driver API is newer than the running eurephia version.  Consider "
                             "to upgrade eurephia to take advantage of newer features in the driver.");
        case 3:
                eDBregister_vpnclientaddr      = eGetSym(ctx, ctx->eurephia_driver, "eDBregister_vpnclientaddr");

        case 2:
#ifdef ENABLE_EUREPHIADM
                if( (ctx->context_type != ECTX_NO_PRIVILEGES) && (ctx->context_type != ECTX_PLUGIN_AUTH) ) {
                        // These functions are only available in admin context
                        eDBadminAuthenticate      = eGetSym(ctx, ctx->eurephia_driver, "eDBadminAuthenticate");
                        eDBadminConfiguration     = eGetSym(ctx, ctx->eurephia_driver, "eDBadminConfiguration");
                        eDBadminUserAccount       = eGetSym(ctx, ctx->eurephia_driver, "eDBadminUserAccount");
                        eDBadminCertificate       = eGetSym(ctx, ctx->eurephia_driver, "eDBadminCertificate");
                        eDBadminUserCertsLink     = eGetSym(ctx, ctx->eurephia_driver, "eDBadminUserCertsLink");
                        eDBadminAccessLevel       = eGetSym(ctx, ctx->eurephia_driver,  "eDBadminAccessLevel");
                        eDBadminFirewallProfiles  = eGetSym(ctx, ctx->eurephia_driver,
                                                            "eDBadminFirewallProfiles");
                        eDBadminGetLastlog        = eGetSym(ctx, ctx->eurephia_driver, "eDBadminGetLastlog");
                        eDBadminAttemptsLog       = eGetSym(ctx, ctx->eurephia_driver, "eDBadminAttemptsLog");
                        eDBadminBlacklist         = eGetSym(ctx, ctx->eurephia_driver, "eDBadminBlacklist");
                }
#endif

        case 1:
                // Setup eDBlink functions
                eDBconnect                     = eGetSym(ctx, ctx->eurephia_driver, "eDBconnect");
                eDBdisconnect                  = eGetSym(ctx, ctx->eurephia_driver, "eDBdisconnect");

                eDBauth_TLS                    = eGetSym(ctx, ctx->eurephia_driver, "eDBauth_TLS");

                eDBauth_user                   = eGetSym(ctx, ctx->eurephia_driver, "eDBauth_user");
                eDBget_uid                     = eGetSym(ctx, ctx->eurephia_driver, "eDBget_uid");

                eDBblacklist_check             = eGetSym(ctx, ctx->eurephia_driver, "eDBblacklist_check");
                eDBregister_attempt            = eGetSym(ctx, ctx->eurephia_driver, "eDBregister_attempt");

                eDBregister_login              = eGetSym(ctx, ctx->eurephia_driver, "eDBregister_login");

                // If api version is 3, this function is replaced by eDBregister_vpnclientaddr()
                eDBregister_vpnmacaddr         = (apiver < 3 ?
                                                  eGetSym(ctx, ctx->eurephia_driver, "eDBregister_vpnmacaddr") : NULL);
                eDBregister_logout             = eGetSym(ctx, ctx->eurephia_driver, "eDBregister_logout");

                eDBget_firewall_profile        = eGetSym(ctx, ctx->eurephia_driver, "eDBget_firewall_profile");
                eDBget_blacklisted_ip          = eGetSym(ctx, ctx->eurephia_driver, "eDBget_blacklisted_ip");

                eDBget_sessionkey_seed         = eGetSym(ctx, ctx->eurephia_driver, "eDBget_sessionkey_seed");
                eDBget_sessionkey_macaddr      = eGetSym(ctx, ctx->eurephia_driver, "eDBget_sessionkey_macaddr");
                eDBcheck_sessionkey_uniqueness = eGetSym(ctx, ctx->eurephia_driver,
                                                         "eDBcheck_sessionkey_uniqueness");

                eDBregister_sessionkey         = eGetSym(ctx, ctx->eurephia_driver, "eDBregister_sessionkey");
                eDBload_sessiondata            = eGetSym(ctx, ctx->eurephia_driver, "eDBload_sessiondata");
                eDBstore_session_value         = eGetSym(ctx, ctx->eurephia_driver, "eDBstore_session_value");
                eDBdestroy_session             = eGetSym(ctx, ctx->eurephia_driver, "eDBdestroy_session");
                break;
        }
        if( ctx->fatal_error > 0 ) {
                eurephia_log(ctx, LOG_FATAL, 0, "The eurephia database driver is not correctly initialised.  "
                             "eurephia authentication will not be available");
                eDBlink_close(ctx);
                return 0;
        }
        return 1;
}
