<commit_before>/**
 * @file
 *
 * @brief filter plugin providing cryptographic operations
 *
 * @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
 *
 */

#ifndef HAVE_KDBCONFIG
#include "kdbconfig.h"
#endif

#include "fcrypt.h"


#include <errno.h>
#include <fcntl.h>
#include <gpg.h>
#include <libgen.h> // provides basename()
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

#include <kdb.h>
#include <kdberrors.h>
#include <kdbmacros.h>
#include <kdbtypes.h>

enum FcryptGetState
{
	PREGETSTORAGE = 0,
	POSTGETSTORAGE = 1
};

struct _fcryptState
{
	enum FcryptGetState getState;
	int tmpFileFd;
	char * tmpFilePath;
	char * originalFilePath;
};
typedef struct _fcryptState fcryptState;

#define ELEKTRA_FCRYPT_TMP_FILE_SUFFIX "XXXXXX"

/**
 * @brief Allocates a new string holding the name of the temporary file.
 * This method makes use of the "fcrypt/tmpdir" plugin configuration option.
 * @param conf holds the plugin configuration
 * @param file holds the path to the original file
 * @param fd will hold the file descriptor to the temporary file in case of success
 * @returns an allocated string holding the name of the encrypted file. Must be freed by the caller.
 */
static char * getTemporaryFileName (KeySet * conf, const char * file, int * fd)
{
	// read the temporary directory to use from the plugin configuration
	const char * tmpDir = ELEKTRA_FCRYPT_DEFAULT_TMPDIR;
	Key * k = ksLookupByName (conf, ELEKTRA_FCRYPT_CONFIG_TMPDIR, 0);
	if (k)
	{
		tmpDir = keyString (k);
	}

	// extract the file name (base name) from the path
	char * fileDup = strdup (file);
	if (!fileDup) goto error;
	const char * baseName = basename (fileDup);

	// + 1 to add an additional '/' as path separator
	// + 1 to reserve space for the NULL terminator
	// ----------------------------------------------
	// + 2 characters in total
	const size_t newFileAllocated = strlen (tmpDir) + strlen (baseName) + strlen (ELEKTRA_FCRYPT_TMP_FILE_SUFFIX) + 2;
	char * newFile = elektraMalloc (newFileAllocated);
	if (!newFile) goto error;
	snprintf (newFile, newFileAllocated, "%s/%s" ELEKTRA_FCRYPT_TMP_FILE_SUFFIX, tmpDir, baseName);
	*fd = mkstemp (newFile);
	if (*fd < 0)
	{
		elektraFree (newFile);
		goto error;
	}

	elektraFree (fileDup);
	return newFile;

error:
	elektraFree (fileDup);
	return NULL;
}

/**
 * @brief Overwrites the content of the given file with zeroes.
 * @param fd holds the file descriptor to the temporary file to be shredded
 * @param errorKey holds an error description in case of failure
 * @retval 1 on success
 * @retval -1 on failure. In this case errorKey holds an error description.
 */
static int shredTemporaryFile (int fd, Key * errorKey)
{
	kdb_octet_t error = 0;
	kdb_octet_t buffer[512] = { 0 };
	struct stat tmpStat;

	if (fstat (fd, &tmpStat))
	{
		ELEKTRA_SET_ERROR (ELEKTRA_ERROR_FCRYPT_TMP_FILE, errorKey, "Failed to retrieve the file status of the temporary file.");
		return -1;
	}

	if (lseek (fd, 0, SEEK_SET))
	{
		goto error;
	}

	for (off_t i = 0; i < tmpStat.st_size; i += sizeof (buffer))
	{
		if (write (fd, buffer, sizeof (buffer)) != sizeof (buffer))
		{
			// save the error state but keep on writing in the hope that further writes wont't fail
			error = 1;
		}
	}
	if (error)
	{
		goto error;
	}

	return 1;

error:
	ELEKTRA_SET_ERROR (ELEKTRA_ERROR_FCRYPT_TMP_FILE, errorKey, "Failed to overwrite the temporary file.");
	return -1;
}<commit_msg>fcrypt: minor improvement in shredTemporaryFile ()<commit_after>/**
 * @file
 *
 * @brief filter plugin providing cryptographic operations
 *
 * @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
 *
 */

#ifndef HAVE_KDBCONFIG
#include "kdbconfig.h"
#endif

#include "fcrypt.h"


#include <errno.h>
#include <fcntl.h>
#include <gpg.h>
#include <libgen.h> // provides basename()
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

#include <kdb.h>
#include <kdberrors.h>
#include <kdbmacros.h>
#include <kdbtypes.h>

enum FcryptGetState
{
	PREGETSTORAGE = 0,
	POSTGETSTORAGE = 1
};

struct _fcryptState
{
	enum FcryptGetState getState;
	int tmpFileFd;
	char * tmpFilePath;
	char * originalFilePath;
};
typedef struct _fcryptState fcryptState;

#define ELEKTRA_FCRYPT_TMP_FILE_SUFFIX "XXXXXX"

/**
 * @brief Allocates a new string holding the name of the temporary file.
 * This method makes use of the "fcrypt/tmpdir" plugin configuration option.
 * @param conf holds the plugin configuration
 * @param file holds the path to the original file
 * @param fd will hold the file descriptor to the temporary file in case of success
 * @returns an allocated string holding the name of the encrypted file. Must be freed by the caller.
 */
static char * getTemporaryFileName (KeySet * conf, const char * file, int * fd)
{
	// read the temporary directory to use from the plugin configuration
	const char * tmpDir = ELEKTRA_FCRYPT_DEFAULT_TMPDIR;
	Key * k = ksLookupByName (conf, ELEKTRA_FCRYPT_CONFIG_TMPDIR, 0);
	if (k)
	{
		tmpDir = keyString (k);
	}

	// extract the file name (base name) from the path
	char * fileDup = strdup (file);
	if (!fileDup) goto error;
	const char * baseName = basename (fileDup);

	// + 1 to add an additional '/' as path separator
	// + 1 to reserve space for the NULL terminator
	// ----------------------------------------------
	// + 2 characters in total
	const size_t newFileAllocated = strlen (tmpDir) + strlen (baseName) + strlen (ELEKTRA_FCRYPT_TMP_FILE_SUFFIX) + 2;
	char * newFile = elektraMalloc (newFileAllocated);
	if (!newFile) goto error;
	snprintf (newFile, newFileAllocated, "%s/%s" ELEKTRA_FCRYPT_TMP_FILE_SUFFIX, tmpDir, baseName);
	*fd = mkstemp (newFile);
	if (*fd < 0)
	{
		elektraFree (newFile);
		goto error;
	}

	elektraFree (fileDup);
	return newFile;

error:
	elektraFree (fileDup);
	return NULL;
}

/**
 * @brief Overwrites the content of the given file with zeroes.
 * @param fd holds the file descriptor to the temporary file to be shredded
 * @param errorKey holds an error description in case of failure
 * @retval 1 on success
 * @retval -1 on failure. In this case errorKey holds an error description.
 */
static int shredTemporaryFile (int fd, Key * errorKey)
{
	kdb_octet_t buffer[512] = { 0 };
	struct stat tmpStat;

	if (fstat (fd, &tmpStat))
	{
		ELEKTRA_SET_ERROR (ELEKTRA_ERROR_FCRYPT_TMP_FILE, errorKey, "Failed to retrieve the file status of the temporary file.");
		return -1;
	}

	if (lseek (fd, 0, SEEK_SET))
	{
		goto error;
	}

	for (off_t i = 0; i < tmpStat.st_size; i += sizeof (buffer))
	{
		if (write (fd, buffer, sizeof (buffer)) != sizeof (buffer))
		{
			goto error;
		}
	}
	return 1;

error:
	ELEKTRA_SET_ERROR (ELEKTRA_ERROR_FCRYPT_TMP_FILE, errorKey, "Failed to overwrite the temporary file.");
	return -1;
}
{'fraction_non_alphanumeric': 0.11918604651162791, 'fraction_numerical': 0.005813953488372093, 'mean_word_length': 3.866336633663366, 'pattern_counts': {'":': 0, '<': 35, '<?xml version=': 0, '>': 31, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5080819', 'n_tokens_mistral': 2505, 'n_tokens_neox': 2380, 'n_words': 802}