mktemp.cpp 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. /*
  2. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/LexicalPath.h>
  7. #include <AK/Random.h>
  8. #include <LibCore/ArgsParser.h>
  9. #include <LibCore/System.h>
  10. #include <LibMain/Main.h>
  11. #include <fcntl.h>
  12. #include <sys/stat.h>
  13. #include <unistd.h>
  14. constexpr StringView default_template = "tmp.XXXXXXXXXX";
  15. static String generate_random_filename(String const& pattern)
  16. {
  17. StringBuilder new_filename { pattern.length() };
  18. constexpr char random_characters[] = "abcdefghijklmnopqrstuvwxyz0123456789";
  19. for (size_t i = 0; i < pattern.length(); i++) {
  20. if (pattern[i] == 'X')
  21. new_filename.append(random_characters[(get_random<u32>() % (sizeof(random_characters) - 1))]);
  22. else
  23. new_filename.append(pattern[i]);
  24. }
  25. return new_filename.to_string();
  26. }
  27. static ErrorOr<String> make_temp(String const& pattern, bool directory, bool dry_run)
  28. {
  29. for (int i = 0; i < 100; ++i) {
  30. auto path = generate_random_filename(pattern);
  31. if (dry_run) {
  32. auto stat_or_error = Core::System::lstat(path.view());
  33. if (stat_or_error.is_error() && stat_or_error.error().code() == ENOENT)
  34. return path;
  35. } else if (directory) {
  36. TRY(Core::System::mkdir(path.view(), 0700));
  37. return path;
  38. } else {
  39. auto fd_or_error = Core::System::open(path.view(), O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
  40. if (!fd_or_error.is_error()) {
  41. TRY(Core::System::close(fd_or_error.value()));
  42. return path;
  43. }
  44. }
  45. }
  46. return String {};
  47. }
  48. ErrorOr<int> serenity_main(Main::Arguments arguments)
  49. {
  50. TRY(Core::System::pledge("stdio rpath wpath cpath"));
  51. StringView file_template;
  52. bool create_directory = false;
  53. bool dry_run = false;
  54. bool quiet = false;
  55. StringView target_directory;
  56. Core::ArgsParser args_parser;
  57. args_parser.set_general_help("Create a temporary file or directory, safely, and print its name.");
  58. args_parser.add_positional_argument(file_template, "The template must contain at least 3 consecutive 'X's", "template", Core::ArgsParser::Required::No);
  59. args_parser.add_option(create_directory, "Create a temporary directory instead of a file", "directory", 'd');
  60. args_parser.add_option(dry_run, "Do not create anything, just print a unique name", "dry-run", 'u');
  61. args_parser.add_option(quiet, "Do not print diagnostics about file/directory creation failure", "quiet", 'q');
  62. args_parser.add_option(target_directory, "Create TEMPLATE relative to DIR", "tmpdir", 'p', "DIR");
  63. args_parser.parse(arguments);
  64. if (target_directory.is_empty()) {
  65. if (!file_template.is_empty()) { // If a custom template is specified we assume the target directory is the current directory
  66. // FIXME: Get rid of this minor memory leak.
  67. auto const* cwd_ptr = getcwd(nullptr, 0);
  68. target_directory = StringView { cwd_ptr, strlen(cwd_ptr) };
  69. } else {
  70. LexicalPath template_path(file_template);
  71. char const* env_directory = getenv("TMPDIR");
  72. target_directory = env_directory && *env_directory ? StringView { env_directory, strlen(env_directory) } : "/tmp"sv;
  73. }
  74. }
  75. if (file_template.is_empty()) {
  76. file_template = default_template;
  77. }
  78. if (!file_template.find("XXX").has_value()) {
  79. if (!quiet)
  80. warnln("Too few X's in template {}", file_template);
  81. return 1;
  82. }
  83. auto target_path = LexicalPath::join(target_directory, file_template).string();
  84. auto final_path = TRY(make_temp(target_path, create_directory, dry_run));
  85. if (final_path.is_null()) {
  86. if (!quiet) {
  87. if (create_directory)
  88. warnln("Failed to create directory via template {}", target_path.characters());
  89. else
  90. warnln("Failed to create file via template {}", target_path.characters());
  91. }
  92. return 1;
  93. }
  94. outln("{}", final_path);
  95. return 0;
  96. }