| 1 | /** |
| 2 | * \file src/system.cc |
| 3 | * \ingroup system |
| 4 | * |
| 5 | * Provide a high-level interface to system-related features, like filesystem manipulations. |
| 6 | * |
| 7 | * Ideally, all OS-specific features should be grouped here. |
| 8 | * |
| 9 | * This modules shoumd not depend on any other opustags module. |
| 10 | */ |
| 11 | |
| 12 | #include <opustags.h> |
| 13 | |
| 14 | #include <errno.h> |
| 15 | #include <fstream> |
| 16 | #include <stdlib.h> |
| 17 | #include <string.h> |
| 18 | #include <sys/stat.h> |
| 19 | #include <sys/wait.h> |
| 20 | #include <unistd.h> |
| 21 | |
| 22 | ot::byte_string operator""_bs(const char* data, size_t size) |
| 23 | { |
| 24 | return ot::byte_string(reinterpret_cast<const uint8_t*>(data), size); |
| 25 | } |
| 26 | |
| 27 | ot::byte_string_view operator""_bsv(const char* data, size_t size) |
| 28 | { |
| 29 | return ot::byte_string_view(reinterpret_cast<const uint8_t*>(data), size); |
| 30 | } |
| 31 | |
| 32 | void ot::partial_file::open(const char* destination) |
| 33 | { |
| 34 | final_name = destination; |
| 35 | temporary_name = final_name + ".XXXXXX.part"; |
| 36 | int fd = mkstemps(const_cast<char*>(temporary_name.data()), 5); |
| 37 | if (fd == -1) |
| 38 | throw status {st::standard_error, |
| 39 | "Could not create a partial file for '" + final_name + "': " + |
| 40 | strerror(errno)}; |
| 41 | file = fdopen(fd, "w"); |
| 42 | if (file == nullptr) |
| 43 | throw status {st::standard_error, |
| 44 | "Could not get the partial file handle to '" + temporary_name + "': " + |
| 45 | strerror(errno)}; |
| 46 | } |
| 47 | |
| 48 | static mode_t get_umask() |
| 49 | { |
| 50 | // libc doesn’t seem to provide a way to get umask without changing it, so we need this workaround. |
| 51 | // https://www.gnu.org/software/libc/manual/html_node/Setting-Permissions.html |
| 52 | mode_t mask = umask(0); |
| 53 | umask(mask); |
| 54 | return mask; |
| 55 | } |
| 56 | |
| 57 | /** |
| 58 | * Try reproducing the file permissions of file `source` onto file `dest`. If |
| 59 | * this fails for whatever reason, print a warning and leave the current |
| 60 | * permissions. When the source doesn’t exist, use the default file creation |
| 61 | * permissions according to umask. |
| 62 | */ |
| 63 | static void copy_permissions(const char* source, const char* dest) |
| 64 | { |
| 65 | mode_t target_mode; |
| 66 | struct stat source_stat; |
| 67 | if (stat(source, &source_stat) == 0) { |
| 68 | // We could technically preserve a bit more than that but who |
| 69 | // would ever need S_ISUID and friends on an Opus file? |
| 70 | target_mode = source_stat.st_mode & 0777; |
| 71 | } else if (errno == ENOENT) { |
| 72 | target_mode = 0666 & ~get_umask(); |
| 73 | } else { |
| 74 | fprintf(stderr, "warning: Could not read mode of %s: %s\n", source, strerror(errno)); |
| 75 | return; |
| 76 | } |
| 77 | if (chmod(dest, target_mode) == -1) |
| 78 | fprintf(stderr, "warning: Could not set mode of %s: %s\n", dest, strerror(errno)); |
| 79 | } |
| 80 | |
| 81 | void ot::partial_file::commit() |
| 82 | { |
| 83 | if (file == nullptr) |
| 84 | return; |
| 85 | file.reset(); |
| 86 | copy_permissions(final_name.c_str(), temporary_name.c_str()); |
| 87 | if (rename(temporary_name.c_str(), final_name.c_str()) == -1) |
| 88 | throw status {st::standard_error, |
| 89 | "Could not move the result file '" + temporary_name + "' to '" + |
| 90 | final_name + "': " + strerror(errno) + "."}; |
| 91 | } |
| 92 | |
| 93 | void ot::partial_file::abort() |
| 94 | { |
| 95 | if (file == nullptr) |
| 96 | return; |
| 97 | file.reset(); |
| 98 | remove(temporary_name.c_str()); |
| 99 | } |
| 100 | |
| 101 | /** |
| 102 | * Determine the file size, in bytes, of the given file. Return -1 on for streams. |
| 103 | */ |
| 104 | static long get_file_size(FILE* f) |
| 105 | { |
| 106 | if (fseek(f, 0L, SEEK_END) != 0) { |
| 107 | clearerr(f); // Recover. |
| 108 | return -1; |
| 109 | } |
| 110 | long file_size = ftell(f); |
| 111 | rewind(f); |
| 112 | return file_size; |
| 113 | } |
| 114 | |
| 115 | ot::byte_string ot::slurp_binary_file(const char* filename) |
| 116 | { |
| 117 | file f = strcmp(filename, "-") == 0 ? freopen(nullptr, "rb", stdin) |
| 118 | : fopen(filename, "rb"); |
| 119 | if (f == nullptr) |
| 120 | throw status { st::standard_error, |
| 121 | "Could not open '"s + filename + "': " + strerror(errno) + "." }; |
| 122 | |
| 123 | byte_string content; |
| 124 | long file_size = get_file_size(f.get()); |
| 125 | if (file_size == -1) { |
| 126 | // Read the input stream block by block and resize the output byte string as needed. |
| 127 | uint8_t buffer[4096]; |
| 128 | while (!feof(f.get())) { |
| 129 | size_t read_len = fread(buffer, 1, sizeof(buffer), f.get()); |
| 130 | content.append(buffer, read_len); |
| 131 | if (ferror(f.get())) |
| 132 | throw status { st::standard_error, |
| 133 | "Could not read '"s + filename + "': " + strerror(errno) + "." }; |
| 134 | } |
| 135 | } else { |
| 136 | // Lucky! We know the file size, so let’s slurp it at once. |
| 137 | content.resize(file_size); |
| 138 | if (fread(content.data(), 1, file_size, f.get()) < file_size) |
| 139 | throw status { st::standard_error, |
| 140 | "Could not read '"s + filename + "': " + strerror(errno) + "." }; |
| 141 | } |
| 142 | |
| 143 | return content; |
| 144 | } |
| 145 | |
| 146 | /** C++ wrapper for iconv. */ |
| 147 | class encoding_converter { |
| 148 | public: |
| 149 | /** |
| 150 | * Allocate the iconv conversion state, initializing the given source and destination |
| 151 | * character encodings. If it's okay to have some information lost, make sure `to` ends with |
| 152 | * "//TRANSLIT", otherwise the conversion will fail when a character cannot be represented |
| 153 | * in the target encoding. See the documentation of iconv_open for details. |
| 154 | */ |
| 155 | encoding_converter(const char* from, const char* to); |
| 156 | ~encoding_converter(); |
| 157 | /** |
| 158 | * Convert text using iconv. If the input sequence is invalid, return #st::badly_encoded and |
| 159 | * abort the processing, leaving out in an undefined state. |
| 160 | */ |
| 161 | template<class InChar, class OutChar> |
| 162 | std::basic_string<OutChar> convert(std::basic_string_view<InChar>); |
| 163 | private: |
| 164 | iconv_t cd; /**< conversion descriptor */ |
| 165 | }; |
| 166 | |
| 167 | encoding_converter::encoding_converter(const char* from, const char* to) |
| 168 | { |
| 169 | cd = iconv_open(to, from); |
| 170 | if (cd == (iconv_t) -1) |
| 171 | throw std::bad_alloc(); |
| 172 | } |
| 173 | |
| 174 | encoding_converter::~encoding_converter() |
| 175 | { |
| 176 | iconv_close(cd); |
| 177 | } |
| 178 | |
| 179 | template<class InChar, class OutChar> |
| 180 | std::basic_string<OutChar> encoding_converter::convert(std::basic_string_view<InChar> in) |
| 181 | { |
| 182 | iconv(cd, nullptr, nullptr, nullptr, nullptr); |
| 183 | std::basic_string<OutChar> out; |
| 184 | out.reserve(in.size()); |
| 185 | const char* in_data = reinterpret_cast<const char*>(in.data()); |
| 186 | char* in_cursor = const_cast<char*>(in_data); |
| 187 | size_t in_left = in.size(); |
| 188 | constexpr size_t chunk_size = 1024; |
| 189 | char chunk[chunk_size]; |
| 190 | for (;;) { |
| 191 | char *out_cursor = chunk; |
| 192 | size_t out_left = chunk_size; |
| 193 | size_t rc = iconv(cd, &in_cursor, &in_left, &out_cursor, &out_left); |
| 194 | |
| 195 | if (rc == (size_t) -1 && errno == E2BIG) { |
| 196 | // Loop normally. |
| 197 | } else if (rc == (size_t) -1) { |
| 198 | throw ot::status {ot::st::badly_encoded, strerror(errno) + "."s}; |
| 199 | } else if (rc != 0) { |
| 200 | throw ot::status {ot::st::badly_encoded, |
| 201 | "Some characters could not be converted into the target encoding."}; |
| 202 | } |
| 203 | |
| 204 | out.append(reinterpret_cast<OutChar*>(chunk), out_cursor - chunk); |
| 205 | if (in_cursor == nullptr) |
| 206 | break; |
| 207 | else if (in_left == 0) |
| 208 | in_cursor = nullptr; |
| 209 | } |
| 210 | return out; |
| 211 | } |
| 212 | |
| 213 | std::u8string ot::encode_utf8(std::string_view in) |
| 214 | { |
| 215 | static encoding_converter to_utf8_cvt("", "UTF-8"); |
| 216 | return to_utf8_cvt.convert<char, char8_t>(in); |
| 217 | } |
| 218 | |
| 219 | std::string ot::decode_utf8(std::u8string_view in) |
| 220 | { |
| 221 | static encoding_converter from_utf8_cvt("UTF-8", ""); |
| 222 | return from_utf8_cvt.convert<char8_t, char>(in); |
| 223 | } |
| 224 | |
| 225 | std::string ot::shell_escape(std::string_view word) |
| 226 | { |
| 227 | std::string escaped_word; |
| 228 | // Pre-allocate the result, assuming most of the time enclosing it in single quotes is enough. |
| 229 | escaped_word.reserve(2 + word.size()); |
| 230 | |
| 231 | escaped_word += '\''; |
| 232 | for (char c : word) { |
| 233 | if (c == '\'') |
| 234 | escaped_word += "'\\''"; |
| 235 | else if (c == '!') |
| 236 | escaped_word += "'\\!'"; |
| 237 | else |
| 238 | escaped_word += c; |
| 239 | } |
| 240 | escaped_word += '\''; |
| 241 | |
| 242 | return escaped_word; |
| 243 | } |
| 244 | |
| 245 | void ot::run_editor(std::string_view editor, std::string_view path) |
| 246 | { |
| 247 | std::string command = std::string(editor) + " " + shell_escape(path); |
| 248 | int status = system(command.c_str()); |
| 249 | |
| 250 | if (status == -1) |
| 251 | throw ot::status {st::standard_error, "waitpid error: "s + strerror(errno)}; |
| 252 | else if (!WIFEXITED(status)) |
| 253 | throw ot::status {st::child_process_failed, |
| 254 | "Child process did not terminate normally: "s + strerror(errno)}; |
| 255 | else if (WEXITSTATUS(status) != 0) |
| 256 | throw ot::status {st::child_process_failed, |
| 257 | "Child process exited with " + std::to_string(WEXITSTATUS(status))}; |
| 258 | } |
| 259 | |
| 260 | timespec ot::get_file_timestamp(const char* path) |
| 261 | { |
| 262 | timespec mtime; |
| 263 | struct stat st; |
| 264 | if (stat(path, &st) == -1) |
| 265 | throw status {st::standard_error, path + ": stat error: "s + strerror(errno)}; |
| 266 | #if defined(HAVE_STAT_ST_MTIM) |
| 267 | mtime = st.st_mtim; |
| 268 | #elif defined(HAVE_STAT_ST_MTIMESPEC) |
| 269 | mtime = st.st_mtimespec; |
| 270 | #else |
| 271 | mtime.tv_sec = st.st_mtime; |
| 272 | mtime.tv_nsec = st.st_mtimensec; |
| 273 | #endif |
| 274 | return mtime; |
| 275 | } |