/*
 *  Copyright (c) 2005-2026, Karsten Ohme
 *  This file is part of GlobalPlatform.
 *
 *  GlobalPlatform is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  GlobalPlatform 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 Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with GlobalPlatform.  If not, see <https://www.gnu.org/licenses/>.
 *
 * In addition, as a special exception, the copyright holders give
 * permission to link the code of portions of this program with the
 * OpenSSL library under certain conditions as described in each
 * individual source file, and distribute linked combinations
 * including the two.
 * You must obey the GNU Lesser General Public License in all respects
 * for all of the code used other than OpenSSL.  If you modify
 * file(s) with this exception, you may extend this exception to your
 * version of the file(s), but you are not obligated to do so.  If you
 * do not wish to do so, delete this exception statement from your
 * version.
 */

/*
 * Based on a implementation from the Muscle MUSCLE SmartCard Development ( http://www.linuxnet.com ) by David Corcoran <corcoran@linuxnet.com>
 */
/**
 * @file
 * @brief This abstracts dynamic library loading functions.
 */

#define _GNU_SOURCE

#include <stdio.h>
#include <string.h>
#ifdef HAVE_DLFCN_H
#include <dlfcn.h>
#include <libgen.h>
#include <stdlib.h>
#include <stdint.h>
#include <limits.h>

#include "globalplatform/debug.h"
#include "globalplatform/error.h"
#include "dyn_generic.h"

#define MAX_LIBRARY_NAME_SIZE 64
#define LIBRARY_NAME_PREFIX _T("lib")
#ifdef __APPLE__
#define LIBRARY_NAME_EXTENSION _T(".dylib")
#else
#define LIBRARY_NAME_EXTENSION _T(".so")
#endif
#define LIBRARY_NAME_VERSION_SEPARATOR _T(".")

static int try_dlopen_relative_to_self(void **handle, const char *soname)
{
	Dl_info info;
	char path[PATH_MAX];
	char dirbuf[PATH_MAX];

	if (dladdr((const void *)(uintptr_t)try_dlopen_relative_to_self, &info) == 0 || !info.dli_fname) {
		return 0; // not tried
	}

	// Copy because dirname may modify buffer
	strncpy(dirbuf, info.dli_fname, sizeof(dirbuf));
	dirbuf[sizeof(dirbuf)-1] = '\0';

	const char *dir = dirname(dirbuf);
	if (!dir) return 0;

	if (snprintf(path, sizeof(path), "%s/%s", dir, soname) <= 0) {
		return 0;
	}

	*handle = dlopen(path, RTLD_LAZY);
	return (*handle != NULL);
}

/**
 * \param libraryHandle [out] The returned library handle
 * \param libraryName [in] The length of the Security Domain AID.
 * \param version [in] The version of the library to use.
 * \return The error status.
 */
OPGP_ERROR_STATUS DYN_LoadLibrary(PVOID *libraryHandle, LPCTSTR libraryName, LPCTSTR version)
{
	OPGP_ERROR_STATUS errorStatus;
	int offset = 0;
	#ifdef __APPLE__
	int i;
	#endif
	*libraryHandle = NULL;
	TCHAR internalLibraryName[MAX_LIBRARY_NAME_SIZE];
	OPGP_LOG_START(_T("DYN_LoadLibrary"));

	OPGP_log_Msg(_T("DYN_LoadLibrary: Using library name \"%s\" and version \"%s\"."), libraryName, version);

	_tcsncpy(internalLibraryName, LIBRARY_NAME_PREFIX, MAX_LIBRARY_NAME_SIZE);
	offset += _tcslen(LIBRARY_NAME_PREFIX);
	_tcsncpy(internalLibraryName + offset, libraryName, MAX_LIBRARY_NAME_SIZE - offset);
	offset +=  _tcslen(libraryName);
	// added version for MacOSX
#ifdef __APPLE__
	if (version != NULL && _tcslen(version) > 0) {
		_tcsncpy(internalLibraryName + offset, LIBRARY_NAME_VERSION_SEPARATOR, MAX_LIBRARY_NAME_SIZE - offset);
		offset += _tcslen(LIBRARY_NAME_VERSION_SEPARATOR);
	    for (i=0; i<_tcslen(version) && offset<MAX_LIBRARY_NAME_SIZE; i++) {
	        if (version[i] == _T('0')) {
	  	        break;
	         }
		    if (version[i] == _T('.')) {
			    continue;
		    }
		    internalLibraryName[offset++] = version[i];	
	    }
	    internalLibraryName[offset] = _T('\0');
	}
#endif
	_tcsncpy(internalLibraryName + offset, LIBRARY_NAME_EXTENSION, MAX_LIBRARY_NAME_SIZE - offset);
	offset += _tcslen(LIBRARY_NAME_EXTENSION);
	// MacOSX uses a different version scheme
#ifndef __APPLE__
	if (version != NULL && _tcslen(version) > 0) {
		_tcsncpy(internalLibraryName + offset, LIBRARY_NAME_VERSION_SEPARATOR, MAX_LIBRARY_NAME_SIZE - offset);
		offset += _tcslen(LIBRARY_NAME_VERSION_SEPARATOR);
		_tcsncpy(internalLibraryName + offset, version, MAX_LIBRARY_NAME_SIZE - offset);
		offset += _tcslen(version);
	}
#endif
	internalLibraryName[MAX_LIBRARY_NAME_SIZE-1] = _T('\0');
	/* If an explicit plugin path is provided, try it first. */
	const char *plugin_path = getenv("OPGP_PLUGIN_PATH");
	if (plugin_path != NULL && plugin_path[0] != '\0') {
		char fullpath[PATH_MAX];
		if (snprintf(fullpath, sizeof(fullpath), "%s/%s", plugin_path, internalLibraryName) > 0) {
			*libraryHandle = dlopen(fullpath, RTLD_LAZY);
		}
	}
	if (*libraryHandle == NULL) {
		try_dlopen_relative_to_self((void**)libraryHandle, internalLibraryName);
	}
	if (*libraryHandle == NULL) {
		*libraryHandle = dlopen(internalLibraryName, RTLD_LAZY);
	}

	if (*libraryHandle == NULL)
	{
		OPGP_ERROR_CREATE_ERROR(errorStatus, -1, dlerror());
		goto end;
	}
	OPGP_ERROR_CREATE_NO_ERROR(errorStatus);

end:
	OPGP_LOG_END(_T("DYN_LoadLibrary"), errorStatus);
	return errorStatus;
}

/**
 * \param libraryHandle [in] The library handle
 * \return The error status.
 */
OPGP_ERROR_STATUS DYN_CloseLibrary(PVOID *libraryHandle)
{
	int ret;
	OPGP_ERROR_STATUS errorStatus;

	OPGP_LOG_START(_T("DYN_CloseLibrary"));
	ret = dlclose(*libraryHandle);
	*libraryHandle = NULL;

	if (ret != 0)
	{
		OPGP_ERROR_CREATE_ERROR(errorStatus, -1, dlerror());
		goto end;
	}
	OPGP_ERROR_CREATE_NO_ERROR(errorStatus);
end:
	OPGP_LOG_END(_T("DYN_CloseLibrary"), errorStatus);
	return errorStatus;
}

/**
 * \param libraryHandle [in] The returned library handle
 * \param functionHandle [out] The returned function handle.
 * \param functionName [in] The function name to search.
 * \return The error status.
 */
OPGP_ERROR_STATUS DYN_GetAddress(PVOID libraryHandle, PVOID *functionHandle, LPCTSTR functionName)
{
	OPGP_ERROR_STATUS errorStatus;
	char pcFunctionName[256];
	const char *dlError = NULL;

	OPGP_LOG_START(_T("DYN_GetAddress"));

	if (functionHandle == NULL || functionName == NULL) {
		OPGP_ERROR_CREATE_ERROR(errorStatus, -1, _T("Invalid arguments to DYN_GetAddress"));
		goto end;
	}

	/* Some platforms might need a leading underscore for the symbol */
	snprintf(pcFunctionName, sizeof(pcFunctionName), "_%s", functionName);

	/* Clear stale loader error state before symbol lookup. */
	dlerror();
	*functionHandle = NULL;
	*functionHandle = dlsym(libraryHandle, functionName);

	/* Failed? Try again with the leading underscore for legacy platforms. */
	if (*functionHandle == NULL)
	{
		dlerror();
		*functionHandle = dlsym(libraryHandle, pcFunctionName);
	}

	if (*functionHandle == NULL)
	{
		dlError = dlerror();
		if (dlError == NULL) {
			dlError = "Unable to resolve symbol";
		}
		OPGP_ERROR_CREATE_ERROR(errorStatus, -1, dlError);
		goto end;
	}
	OPGP_ERROR_CREATE_NO_ERROR(errorStatus);
end:
	OPGP_LOG_END(_T("DYN_GetAddress"), errorStatus);
	return errorStatus;
}

#endif	// HAVE_DLFCN_H
