1 #include "temporary_file.hpp"
2 
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <unistd.h>
8 
9 #include <stdexcept>
10 
11 namespace openpower
12 {
13 namespace pels
14 {
15 namespace util
16 {
17 
18 TemporaryFile::TemporaryFile(const char* data, const uint32_t len)
19 {
20     // Build template path required by mkstemp()
21     std::string templatePath =
22         fs::temp_directory_path() / "phosphor-logging-XXXXXX";
23 
24     // Generate unique file name, create file, and open it.  The XXXXXX
25     // characters are replaced by mkstemp() to make the file name unique.
26     fd = mkostemp(templatePath.data(), O_RDWR);
27     if (fd == -1)
28     {
29         throw std::runtime_error{
30             std::string{"Unable to create temporary file: "} + strerror(errno)};
31     }
32 
33     // Update file with input Buffer data
34     auto rc = write(fd, data, len);
35     if (rc == -1)
36     {
37         // Delete temporary file.  The destructor won't be called because the
38         // exception below causes this constructor to exit without completing.
39         remove();
40         throw std::runtime_error{std::string{"Unable to update file: "} +
41                                  strerror(errno)};
42     }
43 
44     // Store path to temporary file
45     path = templatePath;
46 }
47 
48 TemporaryFile& TemporaryFile::operator=(TemporaryFile&& file)
49 {
50     // Verify not assigning object to itself (a = std::move(a))
51     if (this != &file)
52     {
53         // Delete temporary file owned by this object
54         remove();
55 
56         // Move temporary file path from other object, transferring ownership
57         path = std::move(file.path);
58 
59         // Clear path in other object; after move path is in unspecified state
60         file.path.clear();
61     }
62     return *this;
63 }
64 
65 void TemporaryFile::remove()
66 {
67     if (!path.empty())
68     {
69         // Delete temporary file from file system
70         fs::remove(path);
71 
72         // Clear path to indicate file has been deleted
73         path.clear();
74     }
75 }
76 
77 } // namespace util
78 } // namespace pels
79 } // namespace openpower
80