mktemp.cpp 4.3 KB

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