diff --git a/src/temp_permissions_table.c b/src/temp_permissions_table.c index 8fe4966..cde01c3 100644 --- a/src/temp_permissions_table.c +++ b/src/temp_permissions_table.c @@ -16,6 +16,8 @@ #include #include #include +#include +#include struct temp_process_permissions { // yes, this is a correct type for start time in jiffies (see @@ -27,6 +29,8 @@ struct temp_process_permissions { map(pid_t, struct temp_process_permissions) temp_permissions_table; pthread_mutex_t temp_permissions_table_lock; +pthread_t gc_thread; +int is_gc_active = 0; /** * Function to get the process creation time (in jiffies) from the proc @@ -72,6 +76,47 @@ unsigned long long get_process_creation_time(pid_t pid) { return creation_time; } +int is_valid(pid_t pid, struct temp_process_permissions *entry) { + unsigned long long creation_time = get_process_creation_time(pid); + if (creation_time == 0) { + return 0; + } + + if (creation_time != entry->creation_time) { + return 0; + } + + return 1; +} + +void *garbage_collector(void *arg) { + (void)arg; + + while (is_gc_active) { + sleep(10); + pthread_mutex_lock(&temp_permissions_table_lock); + + vec(pid_t) blacklist; + init(&blacklist); + + for_each(&temp_permissions_table, pid, entry) { + if (!is_valid(*pid, entry)) { + push(&blacklist, *pid); + cleanup(&(entry->allowed_files)); + cleanup(&(entry->denied_files)); + } + } + + for_each(&blacklist, pid) { erase(&temp_permissions_table, *pid); } + + cleanup(&blacklist); + + pthread_mutex_unlock(&temp_permissions_table_lock); + } + + return NULL; +} + /** * Initializes the temporary permissions table. * @@ -82,6 +127,18 @@ int init_temp_permissions_table(void) { init(&temp_permissions_table); return 0; } +/** + * Starts the temporary permissions table garbage_collector. + * + * @return: 0 on success, -1 on failure (e.g. ENOMEM) + */ +int init_garbage_collector(void) { + is_gc_active = 1; + if (pthread_create(&gc_thread, NULL, garbage_collector, NULL) != 0) { + return -1; + } + return 0; +} /** * Destroys the temporary permissions table. @@ -91,6 +148,11 @@ int init_temp_permissions_table(void) { * screwed. */ void destroy_temp_permissions_table(void) { + if (is_gc_active) { + is_gc_active = 0; + pthread_join(gc_thread, NULL); + } + // free the memory allocated for the table for_each(&temp_permissions_table, entry) { for_each(&entry->allowed_files, allowed_file) { free(*allowed_file); }