tempname.c 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. /* Copyright (C) 1991-2022 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. The GNU C Library is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU Lesser General Public
  5. License as published by the Free Software Foundation; either
  6. version 2.1 of the License, or (at your option) any later version.
  7. The GNU C Library is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public
  12. License along with the GNU C Library; if not, see
  13. <https://www.gnu.org/licenses/>. */
  14. #if !_LIBC
  15. # include <libc-config.h>
  16. # include "tempname.h"
  17. #endif
  18. #include <stdbool.h>
  19. #include <errno.h>
  20. #include <stdio.h>
  21. #ifndef TMP_MAX
  22. # define TMP_MAX 238328
  23. #endif
  24. #ifndef __GT_FILE
  25. # define __GT_FILE 0
  26. # define __GT_DIR 1
  27. # define __GT_NOCREATE 2
  28. #endif
  29. #if !_LIBC && (GT_FILE != __GT_FILE || GT_DIR != __GT_DIR \
  30. || GT_NOCREATE != __GT_NOCREATE)
  31. # error report this to bug-gnulib@gnu.org
  32. #endif
  33. #include <stdlib.h>
  34. #include <string.h>
  35. #include <fcntl.h>
  36. #include <stdint.h>
  37. #include <sys/random.h>
  38. #include <sys/stat.h>
  39. #include <time.h>
  40. #if _LIBC
  41. # define struct_stat64 struct __stat64_t64
  42. #else
  43. # define struct_stat64 struct stat
  44. # define __gen_tempname gen_tempname
  45. # define __mkdir mkdir
  46. # define __open open
  47. # define __lstat64_time64(file, buf) lstat (file, buf)
  48. # define __getrandom getrandom
  49. # define __clock_gettime64 clock_gettime
  50. # define __timespec64 timespec
  51. #endif
  52. /* Use getrandom if it works, falling back on a 64-bit linear
  53. congruential generator that starts with Var's value
  54. mixed in with a clock's low-order bits if available. */
  55. typedef uint_fast64_t random_value;
  56. #define RANDOM_VALUE_MAX UINT_FAST64_MAX
  57. #define BASE_62_DIGITS 10 /* 62**10 < UINT_FAST64_MAX */
  58. #define BASE_62_POWER (62LL * 62 * 62 * 62 * 62 * 62 * 62 * 62 * 62 * 62)
  59. /* Return the result of mixing the entropy from R and S.
  60. Assume that R and S are not particularly random,
  61. and that the result should look randomish to an untrained eye. */
  62. static random_value
  63. mix_random_values (random_value r, random_value s)
  64. {
  65. /* As this code is used only when high-quality randomness is neither
  66. available nor necessary, there is no need for fancier polynomials
  67. such as those in the Linux kernel's 'random' driver. */
  68. return (2862933555777941757 * r + 3037000493) ^ s;
  69. }
  70. /* Set *R to a random value.
  71. Return true if *R is set to high-quality value taken from getrandom.
  72. Otherwise return false, falling back to a low-quality *R that might
  73. depend on S.
  74. This function returns false only when getrandom fails.
  75. On GNU systems this should happen only early in the boot process,
  76. when the fallback should be good enough for programs using tempname
  77. because any attacker likely has root privileges already. */
  78. static bool
  79. random_bits (random_value *r, random_value s)
  80. {
  81. /* Without GRND_NONBLOCK it can be blocked for minutes on some systems. */
  82. if (__getrandom (r, sizeof *r, GRND_NONBLOCK) == sizeof *r)
  83. return true;
  84. /* If getrandom did not work, use ersatz entropy based on low-order
  85. clock bits. On GNU systems getrandom should fail only
  86. early in booting, when ersatz should be good enough.
  87. Do not use ASLR-based entropy, as that would leak ASLR info into
  88. the resulting file name which is typically public.
  89. Of course we are in a state of sin here. */
  90. random_value v = s;
  91. #if _LIBC || (defined CLOCK_REALTIME && HAVE_CLOCK_GETTIME)
  92. struct __timespec64 tv;
  93. __clock_gettime64 (CLOCK_REALTIME, &tv);
  94. v = mix_random_values (v, tv.tv_sec);
  95. v = mix_random_values (v, tv.tv_nsec);
  96. #endif
  97. *r = mix_random_values (v, clock ());
  98. return false;
  99. }
  100. #if _LIBC
  101. static int try_tempname_len (char *, int, void *, int (*) (char *, void *),
  102. size_t);
  103. #endif
  104. static int
  105. try_file (char *tmpl, void *flags)
  106. {
  107. int *openflags = flags;
  108. return __open (tmpl,
  109. (*openflags & ~O_ACCMODE)
  110. | O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
  111. }
  112. static int
  113. try_dir (char *tmpl, _GL_UNUSED void *flags)
  114. {
  115. return __mkdir (tmpl, S_IRUSR | S_IWUSR | S_IXUSR);
  116. }
  117. static int
  118. try_nocreate (char *tmpl, _GL_UNUSED void *flags)
  119. {
  120. struct_stat64 st;
  121. if (__lstat64_time64 (tmpl, &st) == 0 || errno == EOVERFLOW)
  122. __set_errno (EEXIST);
  123. return errno == ENOENT ? 0 : -1;
  124. }
  125. /* These are the characters used in temporary file names. */
  126. static const char letters[] =
  127. "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  128. /* Generate a temporary file name based on TMPL. TMPL must match the
  129. rules for mk[s]temp (i.e., end in at least X_SUFFIX_LEN "X"s,
  130. possibly with a suffix).
  131. The name constructed does not exist at the time of the call to
  132. this function. TMPL is overwritten with the result.
  133. KIND may be one of:
  134. __GT_NOCREATE: simply verify that the name does not exist
  135. at the time of the call.
  136. __GT_FILE: create the file using open(O_CREAT|O_EXCL)
  137. and return a read-write fd. The file is mode 0600.
  138. __GT_DIR: create a directory, which will be mode 0700.
  139. */
  140. #ifdef _LIBC
  141. static
  142. #endif
  143. int
  144. gen_tempname_len (char *tmpl, int suffixlen, int flags, int kind,
  145. size_t x_suffix_len)
  146. {
  147. static int (*const tryfunc[]) (char *, void *) =
  148. {
  149. [__GT_FILE] = try_file,
  150. [__GT_DIR] = try_dir,
  151. [__GT_NOCREATE] = try_nocreate
  152. };
  153. return try_tempname_len (tmpl, suffixlen, &flags, tryfunc[kind],
  154. x_suffix_len);
  155. }
  156. #ifdef _LIBC
  157. static
  158. #endif
  159. int
  160. try_tempname_len (char *tmpl, int suffixlen, void *args,
  161. int (*tryfunc) (char *, void *), size_t x_suffix_len)
  162. {
  163. size_t len;
  164. char *XXXXXX;
  165. unsigned int count;
  166. int fd = -1;
  167. int save_errno = errno;
  168. /* A lower bound on the number of temporary files to attempt to
  169. generate. The maximum total number of temporary file names that
  170. can exist for a given template is 62**6. It should never be
  171. necessary to try all of these combinations. Instead if a reasonable
  172. number of names is tried (we define reasonable as 62**3) fail to
  173. give the system administrator the chance to remove the problems.
  174. This value requires that X_SUFFIX_LEN be at least 3. */
  175. #define ATTEMPTS_MIN (62 * 62 * 62)
  176. /* The number of times to attempt to generate a temporary file. To
  177. conform to POSIX, this must be no smaller than TMP_MAX. */
  178. #if ATTEMPTS_MIN < TMP_MAX
  179. unsigned int attempts = TMP_MAX;
  180. #else
  181. unsigned int attempts = ATTEMPTS_MIN;
  182. #endif
  183. /* A random variable. */
  184. random_value v = 0;
  185. /* A value derived from the random variable, and how many random
  186. base-62 digits can currently be extracted from VDIGBUF. */
  187. random_value vdigbuf;
  188. int vdigits = 0;
  189. /* Least biased value for V. If V is less than this, V can generate
  190. BASE_62_DIGITS unbiased digits. Otherwise the digits are biased. */
  191. random_value const biased_min
  192. = RANDOM_VALUE_MAX - RANDOM_VALUE_MAX % BASE_62_POWER;
  193. len = strlen (tmpl);
  194. if (len < x_suffix_len + suffixlen
  195. || strspn (&tmpl[len - x_suffix_len - suffixlen], "X") < x_suffix_len)
  196. {
  197. __set_errno (EINVAL);
  198. return -1;
  199. }
  200. /* This is where the Xs start. */
  201. XXXXXX = &tmpl[len - x_suffix_len - suffixlen];
  202. for (count = 0; count < attempts; ++count)
  203. {
  204. for (size_t i = 0; i < x_suffix_len; i++)
  205. {
  206. if (vdigits == 0)
  207. {
  208. /* Worry about bias only if the bits are high quality. */
  209. while (random_bits (&v, v) && biased_min <= v)
  210. continue;
  211. vdigbuf = v;
  212. vdigits = BASE_62_DIGITS;
  213. }
  214. XXXXXX[i] = letters[vdigbuf % 62];
  215. vdigbuf /= 62;
  216. vdigits--;
  217. }
  218. fd = tryfunc (tmpl, args);
  219. if (fd >= 0)
  220. {
  221. __set_errno (save_errno);
  222. return fd;
  223. }
  224. else if (errno != EEXIST)
  225. return -1;
  226. }
  227. /* We got out of the loop because we ran out of combinations to try. */
  228. __set_errno (EEXIST);
  229. return -1;
  230. }
  231. int
  232. __gen_tempname (char *tmpl, int suffixlen, int flags, int kind)
  233. {
  234. return gen_tempname_len (tmpl, suffixlen, flags, kind, 6);
  235. }
  236. #if !_LIBC
  237. int
  238. try_tempname (char *tmpl, int suffixlen, void *args,
  239. int (*tryfunc) (char *, void *))
  240. {
  241. return try_tempname_len (tmpl, suffixlen, args, tryfunc, 6);
  242. }
  243. #endif