diff --git a/Makefile b/Makefile index 8e801b9..4c39f81 100644 --- a/Makefile +++ b/Makefile @@ -13,6 +13,8 @@ OBJ_FILES := $(patsubst %.c,$(BD)/%.o,$(SRC_FILES)) OBJ_FILES := $(patsubst %.c,$(BD)/%.o,$(SRC_FILES)) SHARED_OBJ_FILES := $(patsubst %.c,$(SBD)/%.o,$(SRC_FILES)) +CFLAGS ?= -O2 -ansi -pedantic + shared: $(SBD)/$(SHARED_LIB) static: $(BD)/$(STATIC_LIB) diff --git a/src/drivers/unix_fs/unix_fs_driver.c b/src/drivers/unix_fs/unix_fs_driver.c index fbf81aa..860be61 100644 --- a/src/drivers/unix_fs/unix_fs_driver.c +++ b/src/drivers/unix_fs/unix_fs_driver.c @@ -84,6 +84,43 @@ deserialize_header(int fd, CommentHeader *header) /* TODO: validate driver_data_ptr */ +FILE * +acquire_id_ctrl_file(char *id_ctrl_file_path) +{ + FILE *retval; + int fd; + + retval = NULL; + + if (!(retval = fopen(id_ctrl_file_path, "r+"))) { + goto defer; + } + + fd = fileno(retval); + + if (lockf(fd, F_LOCK, 0) < 0) { + fclose(retval); + retval = NULL; + goto defer; + } + +defer: + return retval; +} + +int +release_id_ctrl_file(FILE *id_ctrl_file) +{ + int fd; + + fd = fileno(id_ctrl_file); + if (lockf(fd, F_ULOCK, 0) < 0) { + fclose(id_ctrl_file); + return -ENOLCK; + } + return fclose(id_ctrl_file); +} + int unix_fs_driver_leave_comment(void *driver_data_ptr, const CommentHeader *header, const char *text) { @@ -114,21 +151,11 @@ unix_fs_driver_leave_comment(void *driver_data_ptr, const CommentHeader *header, goto defer; } - id_ctrl_file = fopen(id_ctrl_file_path, "r+"); - - if (!id_ctrl_file) { + if (!(id_ctrl_file = acquire_id_ctrl_file(id_ctrl_file_path))) { retval = -EIO; goto defer; } - id_ctrl_fd = fileno(id_ctrl_file); - - if (lockf(id_ctrl_fd, F_LOCK, 0) < 0) { - id_ctrl_fd = -1; - retval = -EIO; - goto defer; - } - if (fscanf(id_ctrl_file, "%d", &max_id) != 1) { max_id = 1; } @@ -161,22 +188,18 @@ unix_fs_driver_leave_comment(void *driver_data_ptr, const CommentHeader *header, if (retval < 0) { goto defer; } - - if (!(id_ctrl_file = freopen(id_ctrl_file_path, "w+", id_ctrl_file))) { - retval = -EIO; - goto defer; - } + + rewind(id_ctrl_file); fprintf(id_ctrl_file, "%d", max_id + 1); /* update id only on success */ retval = max_id + 1; defer: - if (id_ctrl_fd >= 0) { - if (lockf(id_ctrl_fd, F_ULOCK, 0) < 0) { - fprintf(stderr, "Failed to release id control lock, aborting...\n"); + if (id_ctrl_file) { + if (release_id_ctrl_file(id_ctrl_file) < 0) { + fprintf(stderr, "Failed to release id control file, aborting...\n"); abort(); } } - if (id_ctrl_file) fclose(id_ctrl_file); free(id_ctrl_file_path); free(header_file_path); free(text_file_path);