]>
git.proxmox.com Git - libgit2.git/blob - tests/clar/clar/sandbox.h
2 #include <sys/syslimits.h>
5 static char _clar_path
[4096 + 1];
8 is_valid_tmp_path(const char *path
)
12 if (stat(path
, &st
) != 0)
15 if (!S_ISDIR(st
.st_mode
))
18 return (access(path
, W_OK
) == 0);
22 find_tmp_path(char *buffer
, size_t length
)
25 static const size_t var_count
= 5;
26 static const char *env_vars
[] = {
27 "CLAR_TMP", "TMPDIR", "TMP", "TEMP", "USERPROFILE"
32 for (i
= 0; i
< var_count
; ++i
) {
33 const char *env
= getenv(env_vars
[i
]);
37 if (is_valid_tmp_path(env
)) {
39 if (length
>= PATH_MAX
&& realpath(env
, buffer
) != NULL
)
42 strncpy(buffer
, env
, length
- 1);
43 buffer
[length
- 1] = '\0';
48 /* If the environment doesn't say anything, try to use /tmp */
49 if (is_valid_tmp_path("/tmp")) {
51 if (length
>= PATH_MAX
&& realpath("/tmp", buffer
) != NULL
)
54 strncpy(buffer
, "/tmp", length
- 1);
55 buffer
[length
- 1] = '\0';
60 DWORD env_len
= GetEnvironmentVariable("CLAR_TMP", buffer
, (DWORD
)length
);
61 if (env_len
> 0 && env_len
< (DWORD
)length
)
64 if (GetTempPath((DWORD
)length
, buffer
))
68 /* This system doesn't like us, try to use the current directory */
69 if (is_valid_tmp_path(".")) {
70 strncpy(buffer
, ".", length
- 1);
71 buffer
[length
- 1] = '\0';
78 static void clar_unsandbox(void)
80 if (_clar_path
[0] == '\0')
83 cl_must_pass(chdir(".."));
88 static int build_sandbox_path(void)
91 const char path_tail
[] = CLAR_TMPDIR
"_XXXXXX";
93 const char path_tail
[] = "clar_tmp_XXXXXX";
98 if (find_tmp_path(_clar_path
, sizeof(_clar_path
)) < 0)
101 len
= strlen(_clar_path
);
104 { /* normalize path to POSIX forward slashes */
106 for (i
= 0; i
< len
; ++i
) {
107 if (_clar_path
[i
] == '\\')
113 if (_clar_path
[len
- 1] != '/') {
114 _clar_path
[len
++] = '/';
117 strncpy(_clar_path
+ len
, path_tail
, sizeof(_clar_path
) - len
);
119 #if defined(__MINGW32__)
120 if (_mktemp(_clar_path
) == NULL
)
123 if (mkdir(_clar_path
, 0700) != 0)
125 #elif defined(_WIN32)
126 if (_mktemp_s(_clar_path
, sizeof(_clar_path
)) != 0)
129 if (mkdir(_clar_path
, 0700) != 0)
132 if (mkdtemp(_clar_path
) == NULL
)
139 static int clar_sandbox(void)
141 if (_clar_path
[0] == '\0' && build_sandbox_path() < 0)
144 if (chdir(_clar_path
) != 0)
150 const char *clar_sandbox_path(void)