swtpm: Also remove pidfile at end if fd was passed

Address the issue that the pidfile needs to be removed at the end if
a file descriptor was passed in. So we have to look up the file
given the file descriptor and by using /proc/self/fd/.
We also want to make sure that the given file descriptor describes
a regular file.

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
This commit is contained in:
Stefan Berger 2018-04-05 13:12:21 -04:00
parent db60877590
commit f4286d0a0e
4 changed files with 39 additions and 1 deletions

View File

@ -432,6 +432,7 @@ parse_pid_options(char *options, char **pidfile, int *pidfilefd)
OptionValues *ovs = NULL;
char *error = NULL;
const char *filename = NULL;
struct stat stat;
ovs = options_parse(options, pid_opt_desc, &error);
if (!ovs) {
@ -454,6 +455,12 @@ parse_pid_options(char *options, char **pidfile, int *pidfilefd)
logprintf(STDERR_FILENO, "Out of memory.");
goto error;
}
} else {
if (fstat(*pidfilefd, &stat) < 0 || !S_ISREG(stat.st_mode)) {
logprintf(STDERR_FILENO,
"Bad filedescriptor %d for pid file\n", *pidfilefd);
goto error;
}
}
option_values_free(ovs);
@ -462,6 +469,7 @@ parse_pid_options(char *options, char **pidfile, int *pidfilefd)
error:
option_values_free(ovs);
close(*pidfilefd);
return -1;
}

View File

@ -45,6 +45,7 @@
#include "pidfile.h"
#include "logging.h"
#include "utils.h"
static char *g_pidfile;
static int pidfilefd = -1;
@ -82,6 +83,11 @@ int pidfile_write(pid_t pid)
f = fopen(g_pidfile, "w+");
} else if (pidfilefd >= 0) {
f = fdopen(pidfilefd, "w");
if (f) {
g_pidfile = fd_to_filename(pidfilefd);
if (!g_pidfile)
goto error;
}
} else {
return 0;
}
@ -95,7 +101,6 @@ int pidfile_write(pid_t pid)
if (fprintf(f, "%d", pid) < 0) {
logprintf(STDERR_FILENO, "Could not write to pidfile : %s\n",
strerror(errno));
fclose(f);
goto error;
}
@ -104,6 +109,8 @@ int pidfile_write(pid_t pid)
return 0;
error:
if (f)
fclose(f);
return -1;
}

View File

@ -41,6 +41,10 @@
#include <pwd.h>
#include <fcntl.h>
#include <unistd.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "utils.h"
#include "logging.h"
@ -135,3 +139,20 @@ void tpmlib_debug_libtpms_parameters(void)
tpmlib_get_tpm_property(TPMPROP_TPM_MAX_NV_DEFINED_SIZE));
#endif
}
char *fd_to_filename(int fd)
{
char buffer[64];
char *path;
snprintf(buffer, sizeof(buffer), "/proc/self/fd/%d", fd);
path = realpath(buffer, NULL);
if (!path) {
logprintf(STDERR_FILENO, "Could not read %s: %s\n",
buffer, strerror(errno));
return NULL;
}
return path;
}

View File

@ -51,4 +51,6 @@ int change_process_owner(const char *owner);
void tpmlib_debug_libtpms_parameters(void);
char *fd_to_filename(int fd);
#endif /* _SWTPM_UTILS_H_ */