You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
2.4 KiB

  1. /*
  2. ISC License
  3. Copyright (c) 2018, Antonio SJ Musumeci <trapexit@spawn.link>
  4. Permission to use, copy, modify, and/or distribute this software for any
  5. purpose with or without fee is hereby granted, provided that the above
  6. copyright notice and this permission notice appear in all copies.
  7. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  10. ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  12. ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  13. OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. */
  15. #include "errno.hpp"
  16. #include "fs_open.hpp"
  17. #include "fs_path.hpp"
  18. #include "rnd.hpp"
  19. #include <limits.h>
  20. #include <cstdlib>
  21. #include <string>
  22. #include <tuple>
  23. #define PAD_LEN 16
  24. #define MAX_ATTEMPTS 3
  25. static char const CHARS[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  26. static size_t const CHARS_SIZE = (sizeof(CHARS) - 1);
  27. namespace l
  28. {
  29. static
  30. std::string
  31. generate_tmp_path(std::string const base_)
  32. {
  33. fs::Path path;
  34. std::string filename;
  35. filename = '.';
  36. for(int i = 0; i < PAD_LEN; i++)
  37. filename += CHARS[RND::rand64(CHARS_SIZE)];
  38. path = base_;
  39. path /= filename;
  40. return path.string();
  41. }
  42. }
  43. namespace fs
  44. {
  45. std::tuple<int,std::string>
  46. mktemp_in_dir(std::string const dirpath_,
  47. int const flags_)
  48. {
  49. int fd;
  50. int count;
  51. int flags;
  52. std::string tmp_filepath;
  53. fd = -1;
  54. count = MAX_ATTEMPTS;
  55. flags = (flags_ | O_EXCL | O_CREAT | O_TRUNC);
  56. while(count-- > 0)
  57. {
  58. tmp_filepath = l::generate_tmp_path(dirpath_);
  59. fd = fs::open(tmp_filepath,flags,S_IWUSR);
  60. if((fd == -1) && (errno == EEXIST))
  61. continue;
  62. if(fd == -1)
  63. return std::make_tuple(-errno,std::string());
  64. return std::make_tuple(fd,tmp_filepath);
  65. }
  66. return std::make_tuple(-EEXIST,std::string());
  67. }
  68. std::tuple<int,std::string>
  69. mktemp(std::string const filepath_,
  70. int const flags_)
  71. {
  72. ghc::filesystem::path filepath{filepath_};
  73. return fs::mktemp_in_dir(filepath.parent_path(),flags_);
  74. }
  75. }