Update log.c to Solve High CodeQL alert Time-of-check time-of-use filesystem race condition

Fixes a bug found in how log files worked. Feel free to make any changes.
This commit is contained in:
Collin 2025-06-26 19:34:54 -05:00 committed by GitHub
parent 3e1c2d5456
commit 4967b25b95
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -178,24 +178,27 @@ LogFilePrep(const char *fname, const char *backup, const char *idstring)
if (asprintf(&logFileName, fname, idstring) == -1) if (asprintf(&logFileName, fname, idstring) == -1)
FatalError("Cannot allocate space for the log file name\n"); FatalError("Cannot allocate space for the log file name\n");
if (backup && *backup) { int fd = open(logFileName, O_RDWR | O_NOFOLLOW);Add commentMore actions
struct stat buf; if (fd != -1) {
struct stat buf;
if (fstat(fd, &buf) == 0 && S_ISREG(buf.st_mode)) {
char *suffix;
char *oldLog;
if (!stat(logFileName, &buf) && S_ISREG(buf.st_mode)) { if ((asprintf(&suffix, backup, idstring) == -1) ||
char *suffix; (asprintf(&oldLog, "%s%s", logFileName, suffix) == -1)) {
char *oldLog; FatalError("Cannot allocate space for the log file name\n");
}
free(suffix);
if ((asprintf(&suffix, backup, idstring) == -1) || if (renameat(AT_FDCWD, logFileName, AT_FDCWD, oldLog) == -1) {
(asprintf(&oldLog, "%s%s", logFileName, suffix) == -1)) { FatalError("Cannot move old log file \"%s\" to \"%s\"\n",
FatalError("Cannot allocate space for the log file name\n"); logFileName, oldLog);
} }
free(suffix); free(oldLog);
if (rename(logFileName, oldLog) == -1) {
FatalError("Cannot move old log file \"%s\" to \"%s\"\n",
logFileName, oldLog);
} }
free(oldLog); free(oldLog);
close(fd);
} }
} }
else { else {