Skip to content

Commit

Permalink
mktemp: Fix wrong divisor value for modulo operation
Browse files Browse the repository at this point in the history
DONE: RTOS-670
  • Loading branch information
agkaminski committed Nov 7, 2023
1 parent 8e3bfcd commit 44458bf
Showing 1 changed file with 40 additions and 23 deletions.
63 changes: 40 additions & 23 deletions stdlib/mktemp.c
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand All @@ -28,43 +28,60 @@ 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;
}


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)
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit 44458bf

Please sign in to comment.