Added disk operation signatures

This commit is contained in:
2024-02-17 00:57:30 +01:00
parent 044f15dc3c
commit f92c3c6a1e
4 changed files with 85 additions and 18 deletions

View File

@@ -4,6 +4,7 @@
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
bool is_entry_id_valid(const char* entry_id) {
@@ -12,21 +13,30 @@ bool is_entry_id_valid(const char* entry_id) {
size_t length = strlen(entry_id);
// Check that the length is valid
if (length == 0 || length > MAX_ENTRY_LENGTH)
return false;
// Check that the entry id does not contain any slashes
for (size_t i = 0; i < length; i++)
if (entry_id[i] == '/')
return false;
// Check that the entry id is not a reserved name
if (strcmp(entry_id, ".") == 0 || strcmp(entry_id, "..") == 0)
return false;
return true;
}
Result get_entry_path(const char* entry_id, char** out_path) {
*out_path = NULL;
if (!is_entry_id_valid(entry_id))
// Check that the entry id is valid
if (!is_entry_id_valid(entry_id)) {
log_message(LOG_LEVEL_ERROR, "Invalid entry id '%s'.", entry_id);
return FAILURE;
}
return format(out_path, "%s/%s", ENTRY_POOL_DIR, entry_id);
}
@@ -34,17 +44,52 @@ Result get_entry_path(const char* entry_id, char** out_path) {
Result entry_exists(const char* entry_id, bool* out_exists) {
*out_exists = false;
// Get the path of the entry
char* path;
Result result = get_entry_path(entry_id, &path);
if (result != SUCCESS)
return result;
// Check if the entry exists and is a directory
struct stat st;
bool exists = stat(path, &st) == 0 && S_ISDIR(st.st_mode);
// Free the path
free(path);
// Output the result
*out_exists = exists;
return SUCCESS;
}
Result add_entry(const char* entry_id) {
// Check if the entry already exists
bool exists;
Result result = entry_exists(entry_id, &exists);
if (result != SUCCESS)
return result;
if (exists) {
log_message(LOG_LEVEL_ERROR, "Entry '%s' already exists.", entry_id);
return FAILURE;
}
// Create the entry directory
char* path;
result = get_entry_path(entry_id, &path);
if (result != SUCCESS)
return result;
int result_code = mkdir(path, 0755);
free(path);
// Check if the operation failed
if (result_code != 0) {
log_message(LOG_LEVEL_ERROR, "Failed to create entry '%s' (%s).", entry_id, strerror(errno));
return FAILURE;
}
return SUCCESS;
}