7 #include "libutil/File.h"
8 #include "libutil/Log.h"
10 namespace remote
{ namespace util
{
12 std::string
File::readFile(std::string filename
)
18 fd
= open(filename
.c_str(), O_RDONLY
| O_NONBLOCK
);
20 Log::error("open(%s) failed: %s", filename
.c_str(), strerror(errno
));
21 return std::string("");
25 size
= read(fd
, buffer
, sizeof(buffer
) - 1);
26 } while ((size
< 0) && (errno
== EAGAIN
|| errno
== EINTR
));
29 Log::error("read(%s) failed: %s", filename
.c_str(), strerror(errno
));
33 /* Non-blocking, so we should have the full contents now. */
36 /* Sanitize the string to only hold sane ASCII characters. */
37 for (i
= size
- 1; i
>= 0; i
--) {
40 if (c
<= ' ' || c
> 126) {
41 /* Discard cruft at the end. */
48 } else if (c
== '\'' || c
== '"' || c
== '\\') {
56 return std::string(buffer
);
59 std::string
File::readLink(std::string linkname
)
66 buflen
= readlink(linkname
.c_str(), buf
, sizeof(buf
));
68 Log::error("readlink(%s) failed: %s", linkname
.c_str(), strerror(errno
));
69 return std::string("");
75 while (filename
.substr(0, 3) == "../") {
83 if (linkname
.size() >= sizeof(buf
)) {
84 Log::error("Link name too long: %s", linkname
.c_str());
85 return std::string("");
88 linkname
.copy(buf
, linkname
.size());
93 filename
.insert(0, "/");
94 filename
.insert(0, buf
);
99 bool File::writeFile(std::string filename
, const void *data
, uint32_t datalen
)
102 int fd
= open(filename
.c_str(), O_CREAT
| O_TRUNC
| O_WRONLY
, 0644);
105 Log::error("open(%s) failed: %s", filename
.c_str(), strerror(errno
));
109 filesize
= write(fd
, data
, datalen
);
111 Log::error("write(%s) failed: %s", filename
.c_str(), strerror(errno
));
114 if (filesize
== (ssize_t
) datalen
)
117 remove(filename
.c_str());
121 bool File::exists(std::string filename
)
125 return stat(filename
.c_str(), &buf
) >= 0;