libmp/src/ctx/ctx.c

108 lines
2.2 KiB
C

#include "../../include/error.h"
#include "../../include/util.h"
#include "../../include/ctx.h"
#include <linux/limits.h>
#include <stdbool.h>
#include <stdlib.h>
#include <locale.h>
#include <string.h>
#include <stdio.h>
#include <strings.h>
bool __lm_ctx_init_checkdir(char *path){
if(!mkdir_ifnot(path)){
lm_error_set(LM_ERR_FailMkdir);
return false;
}
if(!is_dir(path)){
lm_error_set(LM_ERR_NotDir);
return false;
}
if(!can_write(path)){
lm_error_set(LM_ERR_NoWrite);
return false;
}
return true;
}
bool lm_ctx_init(lm_ctx_t *ctx) {
if(NULL == ctx){
lm_error_set(LM_ERR_ArgNULL);
return false;
}
setlocale(LC_ALL, "");
textdomain("libmp");
bzero(ctx, sizeof(lm_ctx_t));
ctx->version = LM_VERSION;
lm_error_clear();
return true;
}
bool lm_ctx_new(lm_ctx_t *ctx, char *root_dir, char *temp_dir, char *data_dir) {
if(NULL == ctx){
lm_error_set(LM_ERR_ArgNULL);
return false;
}
char *suberr = NULL;
bool ret = false;
lm_ctx_init(ctx);
if(root_dir != NULL && !__lm_ctx_init_checkdir(root_dir)){
suberr = lm_strerror_dup();
pdebug(__func__, "check failed for specified root directory: %s", lm_strerror());
lm_error_set(LM_ERR_CtxRootFail, root_dir, suberr);
goto end;
}
if(root_dir != NULL)
ctx->root = realpath(root_dir, NULL);
if(temp_dir != NULL && !__lm_ctx_init_checkdir(temp_dir)){
suberr = lm_strerror_dup();
pdebug(__func__, "check failed for specified temp directory: %s", lm_strerror());
lm_error_set(LM_ERR_CtxTempFail, temp_dir, suberr);
goto end;
}
if(temp_dir != NULL)
ctx->temp = realpath(temp_dir, NULL);
if(data_dir != NULL && !__lm_ctx_init_checkdir(data_dir)){
suberr = lm_strerror_dup();
pdebug(__func__, "check failed for specified data directory: %s", lm_strerror());
lm_error_set(LM_ERR_CtxDataFail, data_dir, suberr);
goto end;
}
if(data_dir != NULL)
ctx->data = realpath(data_dir, NULL);
ret = true;
end:
free(suberr);
return ret;
}
void lm_ctx_free(lm_ctx_t *ctx) {
lm_ctx_pool_clear(ctx);
free(ctx->data);
free(ctx->root);
free(ctx->temp);
if(NULL != ctx->db)
lm_database_free(ctx->db);
lm_error_clear();
bzero(ctx, sizeof(lm_ctx_t));
return;
}