* Returns -1 on error, 0 if it created a directory, or an open file * descriptor to the created regular file. */
| 434 | * descriptor to the created regular file. |
| 435 | */ |
| 436 | static int git_mkdstemps_mode(char *pattern, int suffix_len, int mode, bool dir) |
| 437 | { |
| 438 | static const char letters[] = |
| 439 | "abcdefghijklmnopqrstuvwxyz" |
| 440 | "ABCDEFGHIJKLMNOPQRSTUVWXYZ" |
| 441 | "0123456789"; |
| 442 | static const int num_letters = ARRAY_SIZE(letters) - 1; |
| 443 | static const char x_pattern[] = "XXXXXX"; |
| 444 | static const int num_x = ARRAY_SIZE(x_pattern) - 1; |
| 445 | char *filename_template; |
| 446 | size_t len; |
| 447 | int fd, count; |
| 448 | |
| 449 | len = strlen(pattern); |
| 450 | |
| 451 | if (len < num_x + suffix_len) { |
| 452 | errno = EINVAL; |
| 453 | return -1; |
| 454 | } |
| 455 | |
| 456 | if (strncmp(&pattern[len - num_x - suffix_len], x_pattern, num_x)) { |
| 457 | errno = EINVAL; |
| 458 | return -1; |
| 459 | } |
| 460 | |
| 461 | /* |
| 462 | * Replace pattern's XXXXXX characters with randomness. |
| 463 | * Try TMP_MAX different filenames. |
| 464 | */ |
| 465 | filename_template = &pattern[len - num_x - suffix_len]; |
| 466 | for (count = 0; count < TMP_MAX; ++count) { |
| 467 | int i; |
| 468 | uint64_t v; |
| 469 | if (csprng_bytes(&v, sizeof(v), 0) < 0) |
| 470 | return error_errno("unable to get random bytes for temporary file"); |
| 471 | |
| 472 | /* Fill in the random bits. */ |
| 473 | for (i = 0; i < num_x; i++) { |
| 474 | filename_template[i] = letters[v % num_letters]; |
| 475 | v /= num_letters; |
| 476 | } |
| 477 | |
| 478 | if (dir) |
| 479 | fd = mkdir(pattern, mode); |
| 480 | else |
| 481 | fd = open(pattern, O_CREAT | O_EXCL | O_RDWR, mode); |
| 482 | if (fd >= 0) |
| 483 | return fd; |
| 484 | /* |
| 485 | * Fatal error (EPERM, ENOSPC etc). |
| 486 | * It doesn't make sense to loop. |
| 487 | */ |
| 488 | if (errno != EEXIST) |
| 489 | break; |
| 490 | } |
| 491 | /* We return the null string if we can't find a unique file name. */ |
| 492 | pattern[0] = '\0'; |
| 493 | return -1; |
no test coverage detected