diff options
Diffstat (limited to 'src/main.c')
| -rw-r--r-- | src/main.c | 66 |
1 files changed, 40 insertions, 26 deletions
@@ -48,6 +48,35 @@ struct parseinfo cached = { 0 }; char *resultdir; int echo = 0, loggedin = 0; +FILE* +lockfile(const char *path, const char* mode, int locktype) +{ + FILE *f; + + if (!(f = fopen(path, mode))) { + ERR("Failed to open index file\n"); + return NULL; + } + if (flock(fileno(f), locktype)) { + fclose(f); + ERR("Failed to acquire lock on index file\n"); + return NULL; + } + fflush(f); /* discard buffered data */ + return f; +} + +void +unlockfile(FILE **f) +{ + if (*f) { + fflush(*f); /* flush output to file */ + flock(fileno(*f), LOCK_UN); + fclose(*f); + *f = NULL; + } +} + int save_submission(struct parseinfo *info, char *stldata, int stlsize) { @@ -72,12 +101,11 @@ save_submission(struct parseinfo *info, char *stldata, int stlsize) FCLOSE(f); indexpath = aprintf("%s/.index", resultdir); - if (!(f = fopen(indexpath, "a+"))) goto fail; - flock(fileno(f), LOCK_EX); + if (!(f = lockfile(indexpath, "a+", LOCK_EX))) + goto exit; fwrite(modeldir, 1, strlen(modeldir), f); fputc('\n', f); - flock(fileno(f), LOCK_UN); - FCLOSE(f); + unlockfile(&f); exit: FCLOSE(f); @@ -280,11 +308,8 @@ search_cmd(const char *arg) /* open and lock index file access */ indexpath = aprintf("%s/.index", resultdir); - if (!(f = fopen(indexpath, "r"))) { - ERR("Sorry, no files currently available\n"); + if (!(f = lockfile(indexpath, "r", LOCK_SH))) goto exit; - } - flock(fileno(f), LOCK_SH); /* output lines that have hash as prefix */ reslen = matchlen = 0; @@ -310,8 +335,7 @@ search_cmd(const char *arg) } } - flock(fileno(f), LOCK_UN); - fclose(f); + unlockfile(&f); if (!reslen) { ERR("Sorry, no files matching that name\n"); @@ -337,7 +361,6 @@ exit: free(filename); free(seldir); free(indexpath); - return; } void @@ -353,14 +376,10 @@ list_cmd(const char *arg) } path = aprintf("%s/.index", resultdir); - if (!(f = fopen(path, "r"))) { - ERR("Failed to get files index\n"); - free(path); - return; - } + f = lockfile(path, "r", LOCK_SH); free(path); + if (!f) return; - flock(fileno(f), LOCK_SH); while (fgets(buf, sizeof(buf), f)) { if (*buf && buf[strlen(buf)-1] == '\n') buf[strlen(buf)-1] = '\0'; @@ -376,8 +395,8 @@ list_cmd(const char *arg) if (fn) fclose(fn); free(path); } - flock(fileno(f), LOCK_UN); - fclose(f); + + unlockfile(&f); } void @@ -409,17 +428,12 @@ auth_cmd(const char *arg) if (!existed) { indexpath = aprintf("%s/.index", resultdir); - if (!(f = fopen(indexpath, "a+"))) { - free(indexpath); - ERR("Auth failed!\n"); + if (!(f = lockfile(indexpath, "a+", LOCK_EX))) return; - } - flock(fileno(f), LOCK_EX); fputc('.', f); fwrite(hash, 1, strlen(hash), f); fputc('\n', f); - flock(fileno(f), LOCK_UN); - fclose(f); + unlockfile(&f); free(indexpath); } |
