1#define _BSD_SOURCE
2#include "libc.h"
3#include <errno.h>
4#include <fcntl.h>
5#include <string.h>
6#include <unistd.h>
7
8char* __randname(char*);
9
10int __mkostemps(char* template, int len, int flags) {
11    size_t l = strlen(template);
12    if (l < 6 || len > l - 6 || memcmp(template + l - len - 6, "XXXXXX", 6)) {
13        errno = EINVAL;
14        return -1;
15    }
16
17    flags -= flags & O_ACCMODE;
18    int fd, retries = 100;
19    do {
20        __randname(template + l - len - 6);
21        if ((fd = open(template, flags | O_RDWR | O_CREAT | O_EXCL, 0600)) >= 0)
22            return fd;
23    } while (--retries && errno == EEXIST);
24
25    memcpy(template + l - len - 6, "XXXXXX", 6);
26    return -1;
27}
28
29weak_alias(__mkostemps, mkostemps);
30weak_alias(__mkostemps, mkostemps64);
31