From 44458bf091eb2e8239319811164f268f4be1c2b7 Mon Sep 17 00:00:00 2001 From: Aleksander Kaminski Date: Mon, 6 Nov 2023 10:46:58 +0100 Subject: [PATCH] mktemp: Fix wrong divisor value for modulo operation DONE: RTOS-670 --- stdlib/mktemp.c | 63 +++++++++++++++++++++++++++++++------------------ 1 file changed, 40 insertions(+), 23 deletions(-) diff --git a/stdlib/mktemp.c b/stdlib/mktemp.c index 460ceec6..f0187ca7 100644 --- a/stdlib/mktemp.c +++ b/stdlib/mktemp.c @@ -5,8 +5,8 @@ * * mktemp.c - create uniquely named files and directories * - * Copyright 2018, 2020 Phoenix Systems - * Author: Kamil Amanowicz, Lukasz Kosinski + * Copyright 2018, 2020, 2023 Phoenix Systems + * Author: Kamil Amanowicz, Lukasz Kosinski, Aleksander Kaminski * * This file is part of Phoenix-RTOS. * @@ -28,35 +28,52 @@ static char pfcs[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345 /* Generates a unique filename */ -static int mktemp(char *templt, int suffixlen) +static int __mktemp(char *templt, int suffixlen) { - int i, len, rand, fd; - char *tail; - oid_t oid; - - if ((templt == NULL) || (suffixlen < 0)) - return -EINVAL; + if ((templt == NULL) || (suffixlen < 0)) { + return SET_ERRNO(-EINVAL); + } - len = strlen(templt); - tail = templt + len - suffixlen - 6; + int len = strlen(templt); + char *tail = templt + len - suffixlen - 6; - if ((len < suffixlen + 6) || strncmp(tail, "XXXXXX", 6)) - return -EINVAL; + if ((len < (suffixlen + 6)) || (strncmp(tail, "XXXXXX", 6) != 0)) { + return SET_ERRNO(-EINVAL); + } - if ((fd = open("/dev/urandom", O_RDONLY)) < 0) + int fd = open("/dev/urandom", O_RDONLY); + if (fd < 0) { + /* errno set by open */ return fd; - - for (i = 0; i < 6; i++) { - read(fd, &rand, sizeof(rand)); - tail[i] = pfcs[rand % sizeof(pfcs)]; } + int rand[6]; + ssize_t left = sizeof(rand); + do { + ssize_t err; + do { + err = read(fd, rand + sizeof(rand) - left, left); + } while ((err < 0) && (errno == -EINTR)); + + if (err <= 0) { + close(fd); + /* errno set by read */ + return -1; + } + left -= err; + } while (left != 0); close(fd); - if (lookup(templt, &oid, NULL) == EOK) - return -EEXIST; + for (int i = 0; i < 6; ++i) { + tail[i] = pfcs[rand[i] % (sizeof(pfcs) - 1)]; + } + + oid_t oid; + if (lookup(templt, &oid, NULL) == 0) { + return SET_ERRNO(-EEXIST); + } - return EOK; + return 0; } @@ -64,7 +81,7 @@ int mkostemps(char *templt, int suffixlen, int flags) { int fd; - if (mktemp(templt, suffixlen) < 0) + if (__mktemp(templt, suffixlen) < 0) return -1; if ((fd = open(templt, (flags & ~0x03) | O_CREAT | O_RDWR | O_EXCL, DEFFILEMODE)) < 0) @@ -94,7 +111,7 @@ int mkstemp(char *templt) char *mkdtemp(char *templt) { - if (mktemp(templt, 0) < 0) + if (__mktemp(templt, 0) < 0) return NULL; if (mkdir(templt, S_IRUSR | S_IWUSR | S_IXUSR) < 0)