mktemp.cpp 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. /*
  2. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@gmail.com>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/LexicalPath.h>
  27. #include <LibCore/ArgsParser.h>
  28. #include <stdio.h>
  29. #include <string.h>
  30. #include <sys/stat.h>
  31. constexpr const char* default_template = "tmp.XXXXXXXXXX";
  32. static char* generate_random_filename(const char* pattern)
  33. {
  34. char* new_filename = strdup(pattern);
  35. int pattern_length = strlen(pattern);
  36. static constexpr char random_characters[] = "abcdefghijklmnopqrstuvwxyz0123456789";
  37. for (auto i = pattern_length - 1; i >= 0; --i) {
  38. if (pattern[i] != 'X')
  39. break;
  40. new_filename[i] = random_characters[(arc4random() % (sizeof(random_characters) - 1))];
  41. }
  42. return new_filename;
  43. }
  44. static char* make_temp(const char* pattern, bool directory, bool dry_run)
  45. {
  46. for (int i = 0; i < 100; ++i) {
  47. char* path = generate_random_filename(pattern);
  48. if (dry_run) {
  49. struct stat stat;
  50. auto rc = lstat(path, &stat);
  51. if (rc < 0 && errno == ENOENT)
  52. return path;
  53. } else if (directory) {
  54. if (!mkdir(path, 0700))
  55. return path;
  56. } else {
  57. auto fd = open(path, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
  58. if (fd >= 0) {
  59. close(fd);
  60. return path;
  61. }
  62. }
  63. free(path);
  64. }
  65. return nullptr;
  66. }
  67. int main(int argc, char** argv)
  68. {
  69. if (pledge("stdio rpath wpath cpath", nullptr)) {
  70. perror("pledge");
  71. return 1;
  72. }
  73. const char* file_template = nullptr;
  74. bool create_directory = false;
  75. bool dry_run = false;
  76. bool quiet = false;
  77. const char* target_directory = nullptr;
  78. Core::ArgsParser args_parser;
  79. args_parser.set_general_help("Create a temporary file or directory, safely, and print its name.");
  80. args_parser.add_positional_argument(file_template, "The template must contain at least 3 consecutive 'X's", "template", Core::ArgsParser::Required::No);
  81. args_parser.add_option(create_directory, "Create a temporary directory instead of a file", "directory", 'd');
  82. args_parser.add_option(dry_run, "Do not create anything, just print a unique name", "dry-run", 'u');
  83. args_parser.add_option(quiet, "Do not print diagnostics about file/directory creation failure", "quiet", 'q');
  84. args_parser.add_option(target_directory, "Create TEMPLATE relative to DIR", "tmpdir", 'p', "DIR");
  85. args_parser.parse(argc, argv);
  86. if (!target_directory) {
  87. if (file_template) { // If a custom template is specified we assume the target directory is the current directory
  88. target_directory = getcwd(nullptr, 0);
  89. } else {
  90. LexicalPath template_path(file_template);
  91. const char* env_directory = getenv("TMPDIR");
  92. target_directory = env_directory && *env_directory ? env_directory : "/tmp";
  93. }
  94. }
  95. if (!file_template) {
  96. file_template = default_template;
  97. }
  98. if (!String(file_template).find("XXX").has_value()) {
  99. if (!quiet)
  100. warnln("Too few X's in template {}", file_template);
  101. return 1;
  102. }
  103. LexicalPath target_path(String::formatted("{}/{}", target_directory, file_template));
  104. if (!target_path.is_valid()) {
  105. if (!quiet)
  106. warnln("Invalid template path {}", target_path.string().characters());
  107. return 1;
  108. }
  109. char* final_path = make_temp(target_path.string().characters(), create_directory, dry_run);
  110. if (!final_path) {
  111. if (!quiet) {
  112. if (create_directory)
  113. warnln("Failed to create directory via template {}", target_path.string().characters());
  114. else
  115. warnln("Failed to create file via template {}", target_path.string().characters());
  116. }
  117. return 1;
  118. }
  119. outln(final_path);
  120. free(final_path);
  121. return 0;
  122. }