Line data Source code
1 : #include "testitall.h"
2 : #include <errno.h>
3 : #include <time.h>
4 :
5 : /**
6 : * @brief Create a unique temporary directory under /tmp and return its path.
7 : *
8 : * Creates /tmp/precizer.XXXXXXXXXXXXXXXXXX where X are random characters
9 : * from [a-zA-Z0-9]. The resulting absolute path is written into the
10 : * caller-provided buffer.
11 : *
12 : * @param path Destination buffer (e.g., char path[PATH_MAX] = {0};).
13 : * @param path_size Size of the destination buffer in bytes (e.g., sizeof(path)).
14 : * @return SUCCESS on success, FAILURE on error or insufficient space.
15 : */
16 1 : Return create_tmpdir(
17 : char *path,
18 : size_t path_size)
19 : {
20 : static bool seeded = false;
21 1 : const char *charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
22 1 : const size_t charset_len = strlen(charset);
23 1 : const size_t suffix_len = 18U; // Number of random characters after the prefix
24 1 : const char *prefix = "/tmp/precizer.";
25 1 : const size_t prefix_len = strlen(prefix);
26 :
27 1 : if(NULL == path || 0U == path_size)
28 : {
29 0 : return(FAILURE);
30 : }
31 :
32 1 : if(prefix_len + suffix_len + 1U > path_size)
33 : {
34 0 : path[0] = '\0';
35 0 : return(FAILURE);
36 : }
37 :
38 1 : if(false == seeded)
39 : {
40 : struct timespec ts;
41 :
42 1 : if(0 == clock_gettime(CLOCK_REALTIME,&ts))
43 : {
44 1 : srand((unsigned int)(ts.tv_nsec ^ ts.tv_sec ^ (unsigned int)getpid()));
45 : } else {
46 0 : srand((unsigned int)time(NULL) ^ (unsigned int)getpid());
47 : }
48 1 : seeded = true;
49 : }
50 :
51 1 : for(int attempt = 0; attempt < 16; attempt++)
52 : {
53 1 : memcpy(path,prefix,prefix_len);
54 :
55 19 : for(size_t i = 0U; i < suffix_len; i++)
56 : {
57 18 : path[prefix_len + i] = charset[(size_t)(rand() % (int)charset_len)];
58 : }
59 :
60 1 : path[prefix_len + suffix_len] = '\0';
61 :
62 1 : if(0 == mkdir(path,0700))
63 : {
64 1 : return(SUCCESS);
65 : }
66 :
67 0 : if(EEXIST != errno)
68 : {
69 0 : path[0] = '\0';
70 0 : return(FAILURE);
71 : }
72 : }
73 :
74 0 : path[0] = '\0';
75 0 : return(FAILURE);
76 : }
|