Line data Source code
1 : /*
2 : * Copyright (C) 2004-2025 Savoir-faire Linux Inc.
3 : *
4 : * This program is free software: you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation, either version 3 of the License, or
7 : * (at your option) any later version.
8 : *
9 : * This program is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * GNU General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU General Public License
15 : * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 : */
17 :
18 : #ifdef HAVE_CONFIG_H
19 : #include "config.h"
20 : #endif
21 :
22 : #include "fileutils.h"
23 : #include "logger.h"
24 : #include "archiver.h"
25 : #include "compiler_intrinsics.h"
26 : #include "base64.h"
27 :
28 : #include <opendht/crypto.h>
29 :
30 : #ifdef __APPLE__
31 : #include <TargetConditionals.h>
32 : #endif
33 :
34 : #if defined(__ANDROID__) || (defined(TARGET_OS_IOS) && TARGET_OS_IOS)
35 : #include "client/ring_signal.h"
36 : #endif
37 :
38 : #ifdef _WIN32
39 : #include <windows.h>
40 : #include "string_utils.h"
41 : #endif
42 :
43 : #include <sys/types.h>
44 : #include <sys/stat.h>
45 :
46 : #ifndef _MSC_VER
47 : #include <libgen.h>
48 : #endif
49 :
50 : #ifdef _MSC_VER
51 : #include "windirent.h"
52 : #else
53 : #include <dirent.h>
54 : #endif
55 :
56 : #include <signal.h>
57 : #include <unistd.h>
58 : #include <fcntl.h>
59 : #ifndef _WIN32
60 : #include <pwd.h>
61 : #else
62 : #include <shlobj.h>
63 : #define NAME_MAX 255
64 : #endif
65 : #if !defined __ANDROID__ && !defined _WIN32
66 : #include <wordexp.h>
67 : #endif
68 :
69 : #include <nettle/sha3.h>
70 :
71 : #include <sstream>
72 : #include <fstream>
73 : #include <iostream>
74 : #include <stdexcept>
75 : #include <limits>
76 : #include <array>
77 :
78 : #include <cstdlib>
79 : #include <cstring>
80 : #include <cerrno>
81 : #include <cstddef>
82 : #include <ciso646>
83 :
84 : #include <pj/ctype.h>
85 : #include <pjlib-util/md5.h>
86 :
87 : #ifndef _MSC_VER
88 : #define PROTECTED_GETENV(str) \
89 : ({ \
90 : char* envvar_ = getenv((str)); \
91 : envvar_ ? envvar_ : ""; \
92 : })
93 :
94 : #define XDG_DATA_HOME (PROTECTED_GETENV("XDG_DATA_HOME"))
95 : #define XDG_CONFIG_HOME (PROTECTED_GETENV("XDG_CONFIG_HOME"))
96 : #define XDG_CACHE_HOME (PROTECTED_GETENV("XDG_CACHE_HOME"))
97 : #else
98 : const wchar_t*
99 : winGetEnv(const wchar_t* name)
100 : {
101 : const DWORD buffSize = 65535;
102 : static wchar_t buffer[buffSize];
103 : if (GetEnvironmentVariable(name, buffer, buffSize)) {
104 : return buffer;
105 : } else {
106 : return L"";
107 : }
108 : }
109 :
110 : #define PROTECTED_GETENV(str) winGetEnv(str)
111 :
112 : #define JAMI_DATA_HOME PROTECTED_GETENV(L"JAMI_DATA_HOME")
113 : #define JAMI_CONFIG_HOME PROTECTED_GETENV(L"JAMI_CONFIG_HOME")
114 : #define JAMI_CACHE_HOME PROTECTED_GETENV(L"JAMI_CACHE_HOME")
115 : #endif
116 :
117 : #define PIDFILE ".ring.pid"
118 : #define ERASE_BLOCK 4096
119 :
120 : namespace jami {
121 : namespace fileutils {
122 :
123 : static std::filesystem::path resource_dir_path;
124 :
125 : void
126 0 : set_resource_dir_path(const std::filesystem::path& resourceDirPath)
127 : {
128 0 : resource_dir_path = resourceDirPath;
129 0 : }
130 :
131 : const std::filesystem::path&
132 816 : get_resource_dir_path()
133 : {
134 816 : static const std::filesystem::path jami_default_data_dir(JAMI_DATADIR);
135 816 : return resource_dir_path.empty() ? jami_default_data_dir : resource_dir_path;
136 : }
137 :
138 : std::string
139 0 : expand_path(const std::string& path)
140 : {
141 : #if defined __ANDROID__ || defined _MSC_VER || defined WIN32 || defined __APPLE__
142 : JAMI_ERR("Path expansion not implemented, returning original");
143 : return path;
144 : #else
145 :
146 0 : std::string result;
147 :
148 : wordexp_t p;
149 0 : int ret = wordexp(path.c_str(), &p, 0);
150 :
151 0 : switch (ret) {
152 0 : case WRDE_BADCHAR:
153 0 : JAMI_ERR("Illegal occurrence of newline or one of |, &, ;, <, >, "
154 : "(, ), {, }.");
155 0 : return result;
156 0 : case WRDE_BADVAL:
157 0 : JAMI_ERR("An undefined shell variable was referenced");
158 0 : return result;
159 0 : case WRDE_CMDSUB:
160 0 : JAMI_ERR("Command substitution occurred");
161 0 : return result;
162 0 : case WRDE_SYNTAX:
163 0 : JAMI_ERR("Shell syntax error");
164 0 : return result;
165 0 : case WRDE_NOSPACE:
166 0 : JAMI_ERR("Out of memory.");
167 : // This is the only error where we must call wordfree
168 0 : break;
169 0 : default:
170 0 : if (p.we_wordc > 0)
171 0 : result = std::string(p.we_wordv[0]);
172 0 : break;
173 : }
174 :
175 0 : wordfree(&p);
176 :
177 0 : return result;
178 : #endif
179 0 : }
180 :
181 : bool
182 2 : isDirectoryWritable(const std::string& directory)
183 : {
184 2 : return accessFile(directory, W_OK) == 0;
185 : }
186 :
187 : bool
188 14 : createSymlink(const std::filesystem::path& linkFile, const std::filesystem::path& target)
189 : {
190 14 : std::error_code ec;
191 14 : std::filesystem::create_symlink(target, linkFile, ec);
192 14 : if (ec) {
193 4 : JAMI_WARNING("Unable to create soft link from {} to {}: {}", linkFile, target, ec.message());
194 1 : return false;
195 : } else {
196 52 : JAMI_LOG("Created soft link from {} to {}", linkFile, target);
197 : }
198 13 : return true;
199 : }
200 :
201 : bool
202 13 : createHardlink(const std::filesystem::path& linkFile, const std::filesystem::path& target)
203 : {
204 13 : std::error_code ec;
205 13 : std::filesystem::create_hard_link(target, linkFile, ec);
206 13 : if (ec) {
207 0 : JAMI_WARNING("Unable to create hard link from {} to {}: {}", linkFile, target, ec.message());
208 0 : return false;
209 : } else {
210 52 : JAMI_LOG("Created hard link from {} to {}", linkFile, target);
211 : }
212 13 : return true;
213 : }
214 :
215 : bool
216 28 : createFileLink(const std::filesystem::path& linkFile, const std::filesystem::path& target, bool hard)
217 : {
218 28 : if (linkFile == target)
219 0 : return true;
220 28 : std::error_code ec;
221 28 : if (std::filesystem::exists(linkFile, ec)) {
222 2 : if (std::filesystem::is_symlink(linkFile, ec) && std::filesystem::read_symlink(linkFile, ec) == target)
223 1 : return true;
224 1 : std::filesystem::remove(linkFile, ec);
225 : }
226 27 : if (not hard or not createHardlink(linkFile, target))
227 14 : return createSymlink(linkFile, target);
228 13 : return true;
229 : }
230 :
231 : std::string_view
232 69 : getFileExtension(std::string_view filename)
233 : {
234 69 : std::string_view result;
235 69 : auto sep = filename.find_last_of('.');
236 69 : if (sep != std::string_view::npos && sep != filename.size() - 1)
237 0 : result = filename.substr(sep + 1);
238 69 : if (result.size() >= 8)
239 0 : return {};
240 69 : return result;
241 : }
242 :
243 : bool
244 9160 : isPathRelative(const std::filesystem::path& path)
245 : {
246 9160 : return not path.empty() and path.is_relative();
247 : }
248 :
249 : std::string
250 10223 : getCleanPath(const std::string& base, const std::string& path)
251 : {
252 10223 : if (base.empty() or path.size() < base.size())
253 10216 : return path;
254 7 : auto base_sep = base + DIR_SEPARATOR_STR;
255 7 : if (path.compare(0, base_sep.size(), base_sep) == 0)
256 7 : return path.substr(base_sep.size());
257 : else
258 0 : return path;
259 7 : }
260 :
261 : std::filesystem::path
262 14378 : getFullPath(const std::filesystem::path& base, const std::filesystem::path& path)
263 : {
264 14378 : bool isRelative {not base.empty() and isPathRelative(path)};
265 14378 : return isRelative ? base / path : path;
266 : }
267 :
268 : std::vector<uint8_t>
269 6777 : loadFile(const std::filesystem::path& path, const std::filesystem::path& default_dir)
270 : {
271 10881 : return dhtnet::fileutils::loadFile(getFullPath(default_dir, path));
272 : }
273 :
274 : std::string
275 7 : loadTextFile(const std::filesystem::path& path, const std::filesystem::path& default_dir)
276 : {
277 7 : std::string buffer;
278 7 : auto fullPath = getFullPath(default_dir, path);
279 :
280 : // Open with explicit share mode to allow reading even if file is opened elsewhere
281 : #ifdef _WIN32
282 : std::ifstream file(fullPath, std::ios::in | std::ios::binary, _SH_DENYNO);
283 : #else
284 7 : std::ifstream file(fullPath);
285 : #endif
286 :
287 7 : if (!file)
288 3 : throw std::runtime_error("Unable to read file: " + path.string());
289 :
290 4 : file.seekg(0, std::ios::end);
291 4 : auto size = file.tellg();
292 4 : if (size > std::numeric_limits<unsigned>::max())
293 0 : throw std::runtime_error("File is too big: " + path.string());
294 4 : buffer.resize(size);
295 4 : file.seekg(0, std::ios::beg);
296 4 : if (!file.read((char*) buffer.data(), size))
297 0 : throw std::runtime_error("Unable to load file: " + path.string());
298 8 : return buffer;
299 13 : }
300 :
301 : void
302 1569 : saveFile(const std::filesystem::path& path, const uint8_t* data, size_t data_size, mode_t UNUSED mode)
303 : {
304 1569 : std::ofstream file(path, std::ios::trunc | std::ios::binary);
305 1569 : if (!file.is_open()) {
306 8 : JAMI_ERROR("Unable to write data to {}", path);
307 2 : return;
308 : }
309 1567 : file.write((char*) data, data_size);
310 : #ifndef _WIN32
311 1567 : file.close();
312 1567 : if (chmod(path.c_str(), mode) < 0)
313 0 : JAMI_WARNING("fileutils::saveFile(): chmod() failed on {}, {}", path, strerror(errno));
314 : #endif
315 1569 : }
316 :
317 : std::vector<uint8_t>
318 0 : loadCacheFile(const std::filesystem::path& path, std::chrono::system_clock::duration maxAge)
319 : {
320 : // last_write_time throws exception if file doesn't exist
321 0 : std::error_code ec;
322 0 : auto writeTime = std::filesystem::last_write_time(path, ec);
323 0 : if (ec)
324 0 : throw std::runtime_error("unable to get last write time of file");
325 0 : auto now = decltype(writeTime)::clock::now();
326 0 : if (now - writeTime > maxAge)
327 0 : throw std::runtime_error("file too old " + dht::print_time_relative(now, writeTime));
328 :
329 0 : JAMI_LOG("Loading cache file '{}'", path);
330 0 : return dhtnet::fileutils::loadFile(path);
331 : }
332 :
333 : std::string
334 0 : loadCacheTextFile(const std::filesystem::path& path, std::chrono::system_clock::duration maxAge)
335 : {
336 : // last_write_time throws exception if file doesn't exist
337 0 : std::error_code ec;
338 0 : auto writeTime = std::filesystem::last_write_time(path, ec);
339 0 : if (ec)
340 0 : throw std::runtime_error("unable to get last write time of file");
341 0 : auto now = decltype(writeTime)::clock::now();
342 0 : if (now - writeTime > maxAge)
343 0 : throw std::runtime_error("file too old " + dht::print_time_relative(now, writeTime));
344 :
345 0 : JAMI_LOG("Loading cache file '{}'", path);
346 0 : return loadTextFile(path);
347 : }
348 :
349 : ArchiveStorageData
350 103 : readArchive(const std::filesystem::path& path, std::string_view scheme, const std::string& pwd)
351 : {
352 412 : JAMI_LOG("Reading archive from {} with scheme '{}'", path, scheme);
353 :
354 192 : auto isUnencryptedGzip = [](const std::vector<uint8_t>& data) {
355 : // NOTE: some webserver modify gzip files and this can end with a gunzip in a gunzip
356 : // file. So, to make the readArchive more robust, we can support this case by detecting
357 : // gzip header via 1f8b 08
358 : // We don't need to support more than 2 level, else somebody may be able to send
359 : // gunzip in loops and abuse.
360 192 : return data.size() > 3 && data[0] == 0x1f && data[1] == 0x8b && data[2] == 0x08;
361 : };
362 :
363 101 : auto decompress = [](std::vector<uint8_t>& data) {
364 : try {
365 101 : data = archiver::decompress(data);
366 0 : } catch (const std::exception& e) {
367 0 : JAMI_ERROR("Error decrypting archive: {}", e.what());
368 0 : throw e;
369 0 : }
370 101 : };
371 :
372 103 : std::vector<uint8_t> fileContent;
373 :
374 : // Read file
375 : try {
376 103 : fileContent = dhtnet::fileutils::loadFile(path);
377 0 : } catch (const std::exception& e) {
378 0 : JAMI_ERROR("Error loading archive: {}", e.what());
379 0 : throw;
380 0 : }
381 :
382 103 : if (isUnencryptedGzip(fileContent)) {
383 90 : if (!pwd.empty())
384 8 : JAMI_WARNING("A gunzip in a gunzip is detected. A webserver may have a bad config");
385 90 : decompress(fileContent);
386 : }
387 :
388 103 : ArchiveStorageData ret;
389 : // ret.data = {fileContent.data(), fileContent.data()+fileContent.size()};
390 :
391 103 : if (!pwd.empty()) {
392 : // Decrypt
393 14 : if (scheme == ARCHIVE_AUTH_SCHEME_KEY) {
394 : try {
395 0 : ret.salt = dht::crypto::aesGetSalt(fileContent);
396 0 : fileContent = dht::crypto::aesDecrypt(dht::crypto::aesGetEncrypted(fileContent), base64::decode(pwd));
397 0 : } catch (const std::exception& e) {
398 0 : JAMI_ERROR("Error decrypting archive: {}", e.what());
399 0 : throw;
400 0 : }
401 14 : } else if (scheme == ARCHIVE_AUTH_SCHEME_PASSWORD) {
402 : try {
403 14 : ret.salt = dht::crypto::aesGetSalt(fileContent);
404 14 : fileContent = dht::crypto::aesDecrypt(fileContent, pwd);
405 4 : } catch (const std::exception& e) {
406 16 : JAMI_ERROR("Error decrypting archive: {}", e.what());
407 4 : throw;
408 4 : }
409 : }
410 10 : decompress(fileContent);
411 89 : } else if (isUnencryptedGzip(fileContent)) {
412 4 : JAMI_WARNING("A gunzip in a gunzip is detected. A webserver may have a bad config");
413 1 : decompress(fileContent);
414 : }
415 99 : ret.data = {fileContent.data(), fileContent.data() + fileContent.size()};
416 198 : return ret;
417 107 : }
418 :
419 : bool
420 818 : writeArchive(const std::string& archive_str,
421 : const std::filesystem::path& path,
422 : std::string_view scheme,
423 : const std::string& password,
424 : const std::vector<uint8_t>& password_salt)
425 : {
426 3272 : JAMI_LOG("Writing archive to {} using scheme '{}'", path, scheme);
427 :
428 818 : if (scheme == ARCHIVE_AUTH_SCHEME_KEY) {
429 : // Encrypt using provided key
430 : try {
431 0 : auto key = base64::decode(password);
432 0 : auto newArchive = dht::crypto::aesEncrypt(archiver::compress(archive_str), key);
433 0 : saveFile(path, dht::crypto::aesBuildEncrypted(newArchive, password_salt));
434 0 : } catch (const std::runtime_error& ex) {
435 0 : JAMI_ERROR("Export failed: {}", ex.what());
436 0 : return false;
437 0 : }
438 818 : } else if (scheme == ARCHIVE_AUTH_SCHEME_PASSWORD and not password.empty()) {
439 : // Encrypt using provided password
440 : try {
441 18 : saveFile(path, dht::crypto::aesEncrypt(archiver::compress(archive_str), password, password_salt));
442 0 : } catch (const std::runtime_error& ex) {
443 0 : JAMI_ERROR("Export failed: {}", ex.what());
444 0 : return false;
445 0 : }
446 800 : } else if (scheme == ARCHIVE_AUTH_SCHEME_NONE || (scheme == ARCHIVE_AUTH_SCHEME_PASSWORD && password.empty())) {
447 3200 : JAMI_WARNING("Unsecured archiving (no password)");
448 800 : archiver::compressGzip(archive_str, path.string());
449 : } else {
450 0 : JAMI_ERROR("Unsupported scheme: {}", scheme);
451 0 : return false;
452 : }
453 818 : return true;
454 : }
455 :
456 : std::filesystem::path
457 64 : get_cache_dir([[maybe_unused]] const char* pkg)
458 : {
459 : #if defined(__ANDROID__) || (defined(TARGET_OS_IOS) && TARGET_OS_IOS)
460 : std::vector<std::string> paths;
461 : paths.reserve(1);
462 : emitSignal<libjami::ConfigurationSignal::GetAppDataPath>("cache", &paths);
463 : if (not paths.empty())
464 : return paths[0];
465 : return {};
466 : #elif defined(__APPLE__)
467 : return get_home_dir() / "Library" / "Caches" / pkg;
468 : #else
469 : #ifdef _WIN32
470 : const std::wstring cache_home(JAMI_CACHE_HOME);
471 : if (not cache_home.empty())
472 : return jami::to_string(cache_home);
473 : #else
474 64 : const std::string cache_home(XDG_CACHE_HOME);
475 64 : if (not cache_home.empty())
476 0 : return cache_home;
477 : #endif
478 128 : return get_home_dir() / ".cache" / pkg;
479 : #endif
480 64 : }
481 :
482 : const std::filesystem::path&
483 3279 : get_cache_dir()
484 : {
485 3279 : static const std::filesystem::path cache_dir = get_cache_dir(PACKAGE);
486 3279 : return cache_dir;
487 : }
488 :
489 : std::filesystem::path
490 33 : get_home_dir_impl()
491 : {
492 : #if defined(__ANDROID__) || (defined(TARGET_OS_IOS) && TARGET_OS_IOS)
493 : std::vector<std::string> paths;
494 : paths.reserve(1);
495 : emitSignal<libjami::ConfigurationSignal::GetAppDataPath>("files", &paths);
496 : if (not paths.empty())
497 : return paths[0];
498 : return {};
499 : #elif defined _WIN32
500 : TCHAR path[MAX_PATH];
501 : if (SUCCEEDED(SHGetFolderPath(nullptr, CSIDL_PROFILE, nullptr, 0, path))) {
502 : return jami::to_string(path);
503 : }
504 : return {};
505 : #else
506 :
507 : // 1) try getting user's home directory from the environment
508 33 : std::string home(PROTECTED_GETENV("HOME"));
509 33 : if (not home.empty())
510 33 : return home;
511 :
512 : // 2) try getting it from getpwuid_r (i.e. /etc/passwd)
513 0 : const long max = sysconf(_SC_GETPW_R_SIZE_MAX);
514 0 : if (max != -1) {
515 0 : char buf[max];
516 : struct passwd pwbuf, *pw;
517 0 : if (getpwuid_r(getuid(), &pwbuf, buf, sizeof(buf), &pw) == 0 and pw != NULL)
518 0 : return pw->pw_dir;
519 0 : }
520 :
521 0 : return {};
522 : #endif
523 33 : }
524 :
525 : const std::filesystem::path&
526 195 : get_home_dir()
527 : {
528 195 : static const std::filesystem::path home_dir = get_home_dir_impl();
529 195 : return home_dir;
530 : }
531 :
532 : std::filesystem::path
533 64 : get_data_dir([[maybe_unused]] const char* pkg)
534 : {
535 : #if defined(__ANDROID__) || (defined(TARGET_OS_IOS) && TARGET_OS_IOS)
536 : std::vector<std::string> paths;
537 : paths.reserve(1);
538 : emitSignal<libjami::ConfigurationSignal::GetAppDataPath>("files", &paths);
539 : if (not paths.empty())
540 : return paths[0];
541 : return {};
542 : #elif defined(__APPLE__)
543 : return get_home_dir() / "Library" / "Application Support" / pkg;
544 : #elif defined(_WIN32)
545 : std::wstring data_home(JAMI_DATA_HOME);
546 : if (not data_home.empty())
547 : return std::filesystem::path(data_home) / pkg;
548 :
549 : if (!strcmp(pkg, "ring")) {
550 : return get_home_dir() / ".local" / "share" / pkg;
551 : } else {
552 : return get_home_dir() / "AppData" / "Local" / pkg;
553 : }
554 : #else
555 64 : std::string_view data_home(XDG_DATA_HOME);
556 64 : if (not data_home.empty())
557 0 : return std::filesystem::path(data_home) / pkg;
558 : // "If $XDG_DATA_HOME is either not set or empty, a default equal to
559 : // $HOME/.local/share should be used."
560 128 : return get_home_dir() / ".local" / "share" / pkg;
561 : #endif
562 : }
563 :
564 : const std::filesystem::path&
565 61213 : get_data_dir()
566 : {
567 61213 : static const std::filesystem::path data_dir = get_data_dir(PACKAGE);
568 61215 : return data_dir;
569 : }
570 :
571 : std::filesystem::path
572 65 : get_config_dir([[maybe_unused]] const char* pkg)
573 : {
574 65 : std::filesystem::path configdir;
575 : #if defined(__ANDROID__) || (defined(TARGET_OS_IOS) && TARGET_OS_IOS)
576 : std::vector<std::string> paths;
577 : emitSignal<libjami::ConfigurationSignal::GetAppDataPath>("config", &paths);
578 : if (not paths.empty())
579 : configdir = std::filesystem::path(paths[0]);
580 : #elif defined(__APPLE__)
581 : configdir = fileutils::get_home_dir() / "Library" / "Application Support" / pkg;
582 : #elif defined(_WIN32)
583 : std::wstring xdg_env(JAMI_CONFIG_HOME);
584 : if (not xdg_env.empty()) {
585 : configdir = std::filesystem::path(xdg_env) / pkg;
586 : } else if (!strcmp(pkg, "ring")) {
587 : configdir = fileutils::get_home_dir() / ".config" / pkg;
588 : } else {
589 : configdir = fileutils::get_home_dir() / "AppData" / "Local" / pkg;
590 : }
591 : #else
592 65 : std::string xdg_env(XDG_CONFIG_HOME);
593 65 : if (not xdg_env.empty())
594 0 : configdir = std::filesystem::path(xdg_env) / pkg;
595 : else
596 65 : configdir = fileutils::get_home_dir() / ".config" / pkg;
597 : #endif
598 65 : if (!dhtnet::fileutils::recursive_mkdir(configdir, 0700)) {
599 : // If directory creation failed
600 0 : if (errno != EEXIST)
601 0 : JAMI_DBG("Unable to create directory: %s!", configdir.c_str());
602 : }
603 130 : return configdir;
604 65 : }
605 :
606 : const std::filesystem::path&
607 265 : get_config_dir()
608 : {
609 265 : static const std::filesystem::path config_dir = get_config_dir(PACKAGE);
610 265 : return config_dir;
611 : }
612 :
613 : #ifdef _WIN32
614 : bool
615 : eraseFile_win32(const std::string& path, bool dosync)
616 : {
617 : // Note: from
618 : // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-deletefilea#remarks To
619 : // delete a read-only file, first you must remove the read-only attribute.
620 : SetFileAttributesA(path.c_str(), GetFileAttributesA(path.c_str()) & ~FILE_ATTRIBUTE_READONLY);
621 : HANDLE h = CreateFileA(path.c_str(), GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
622 : if (h == INVALID_HANDLE_VALUE) {
623 : JAMI_WARN("Unable to open file %s for erasing.", path.c_str());
624 : return false;
625 : }
626 :
627 : LARGE_INTEGER size;
628 : if (!GetFileSizeEx(h, &size)) {
629 : JAMI_WARN("Unable to erase file %s: GetFileSizeEx() failed.", path.c_str());
630 : CloseHandle(h);
631 : return false;
632 : }
633 : if (size.QuadPart == 0) {
634 : CloseHandle(h);
635 : return false;
636 : }
637 :
638 : uint64_t size_blocks = size.QuadPart / ERASE_BLOCK;
639 : if (size.QuadPart % ERASE_BLOCK)
640 : size_blocks++;
641 :
642 : char* buffer;
643 : try {
644 : buffer = new char[ERASE_BLOCK];
645 : } catch (std::bad_alloc& ba) {
646 : JAMI_WARN("Unable to allocate buffer for erasing %s.", path.c_str());
647 : CloseHandle(h);
648 : return false;
649 : }
650 : memset(buffer, 0x00, ERASE_BLOCK);
651 :
652 : OVERLAPPED ovlp;
653 : if (size.QuadPart < (1024 - 42)) { // a small file can be stored in the MFT record
654 : ovlp.Offset = 0;
655 : ovlp.OffsetHigh = 0;
656 : WriteFile(h, buffer, (DWORD) size.QuadPart, 0, &ovlp);
657 : FlushFileBuffers(h);
658 : }
659 : for (uint64_t i = 0; i < size_blocks; i++) {
660 : uint64_t offset = i * ERASE_BLOCK;
661 : ovlp.Offset = offset & 0x00000000FFFFFFFF;
662 : ovlp.OffsetHigh = offset >> 32;
663 : WriteFile(h, buffer, ERASE_BLOCK, 0, &ovlp);
664 : }
665 :
666 : delete[] buffer;
667 :
668 : if (dosync)
669 : FlushFileBuffers(h);
670 :
671 : CloseHandle(h);
672 : return true;
673 : }
674 :
675 : #else
676 :
677 : bool
678 0 : eraseFile_posix(const std::string& path, bool dosync)
679 : {
680 : struct stat st;
681 0 : if (stat(path.c_str(), &st) == -1) {
682 0 : JAMI_WARN("Unable to erase file %s: fstat() failed.", path.c_str());
683 0 : return false;
684 : }
685 : // Remove read-only flag if possible
686 0 : chmod(path.c_str(), st.st_mode | (S_IWGRP + S_IWUSR));
687 :
688 0 : int fd = open(path.c_str(), O_WRONLY);
689 0 : if (fd == -1) {
690 0 : JAMI_WARN("Unable to open file %s for erasing.", path.c_str());
691 0 : return false;
692 : }
693 :
694 0 : if (st.st_size == 0) {
695 0 : close(fd);
696 0 : return false;
697 : }
698 :
699 0 : lseek(fd, 0, SEEK_SET);
700 :
701 : std::array<char, ERASE_BLOCK> buffer;
702 0 : buffer.fill(0);
703 0 : decltype(st.st_size) written(0);
704 0 : while (written < st.st_size) {
705 0 : auto ret = write(fd, buffer.data(), buffer.size());
706 0 : if (ret < 0) {
707 0 : JAMI_WARNING("Error while overriding file with zeros.");
708 0 : break;
709 : } else
710 0 : written += ret;
711 : }
712 :
713 0 : if (dosync)
714 0 : fsync(fd);
715 :
716 0 : close(fd);
717 0 : return written >= st.st_size;
718 : }
719 : #endif
720 :
721 : bool
722 0 : eraseFile(const std::string& path, bool dosync)
723 : {
724 : #ifdef _WIN32
725 : return eraseFile_win32(path, dosync);
726 : #else
727 0 : return eraseFile_posix(path, dosync);
728 : #endif
729 : }
730 :
731 : int
732 0 : remove(const std::filesystem::path& path, bool erase)
733 : {
734 0 : if (erase and dhtnet::fileutils::isFile(path, false) and !dhtnet::fileutils::hasHardLink(path))
735 0 : eraseFile(path.string(), true);
736 :
737 : #ifdef _WIN32
738 : // use Win32 api since std::remove will not unlink directory in use
739 : if (std::filesystem::is_directory(path))
740 : return !RemoveDirectory(path.c_str());
741 : #endif
742 :
743 0 : return std::remove(path.string().c_str());
744 : }
745 :
746 : int64_t
747 42 : size(const std::filesystem::path& path)
748 : {
749 42 : int64_t size = 0;
750 : try {
751 42 : std::ifstream file(path, std::ios::binary | std::ios::in);
752 42 : file.seekg(0, std::ios_base::end);
753 42 : size = file.tellg();
754 42 : file.close();
755 42 : } catch (...) {
756 0 : }
757 42 : return size;
758 : }
759 :
760 : std::string
761 47 : sha3File(const std::filesystem::path& path)
762 : {
763 : sha3_512_ctx ctx;
764 47 : sha3_512_init(&ctx);
765 :
766 : try {
767 47 : if (not std::filesystem::is_regular_file(path)) {
768 0 : JAMI_ERROR("Unable to compute sha3sum of {}: not a regular file", path);
769 0 : return {};
770 : }
771 47 : std::ifstream file(path, std::ios::binary | std::ios::in);
772 47 : if (!file) {
773 0 : JAMI_ERROR("Unable to compute sha3sum of {}: failed to open file", path);
774 0 : return {};
775 : }
776 47 : std::vector<char> buffer(8192, 0);
777 6937 : while (!file.eof()) {
778 6890 : file.read(buffer.data(), buffer.size());
779 6890 : std::streamsize readSize = file.gcount();
780 6890 : sha3_512_update(&ctx, readSize, (const uint8_t*) buffer.data());
781 : }
782 47 : } catch (const std::exception& e) {
783 0 : JAMI_ERROR("Unable to compute sha3sum of {}: {}", path, e.what());
784 0 : return {};
785 0 : }
786 :
787 : unsigned char digest[SHA3_512_DIGEST_SIZE];
788 47 : sha3_512_digest(&ctx, SHA3_512_DIGEST_SIZE, digest);
789 :
790 : char hash[SHA3_512_DIGEST_SIZE * 2];
791 :
792 3055 : for (int i = 0; i < SHA3_512_DIGEST_SIZE; ++i)
793 3008 : pj_val_to_hex_digit(digest[i], &hash[2 * i]);
794 :
795 47 : return {hash, SHA3_512_DIGEST_SIZE * 2};
796 : }
797 :
798 : std::string
799 0 : sha3sum(const uint8_t* data, size_t size)
800 : {
801 : sha3_512_ctx ctx;
802 0 : sha3_512_init(&ctx);
803 0 : sha3_512_update(&ctx, size, data);
804 : unsigned char digest[SHA3_512_DIGEST_SIZE];
805 0 : sha3_512_digest(&ctx, SHA3_512_DIGEST_SIZE, digest);
806 0 : return dht::toHex(digest, SHA3_512_DIGEST_SIZE);
807 : }
808 :
809 : int
810 2 : accessFile(const std::string& file, int mode)
811 : {
812 : #ifdef _WIN32
813 : return _waccess(jami::to_wstring(file).c_str(), mode);
814 : #else
815 2 : return access(file.c_str(), mode);
816 : #endif
817 : }
818 :
819 : uint64_t
820 16 : lastWriteTimeInSeconds(const std::filesystem::path& filePath)
821 : {
822 16 : std::error_code ec;
823 16 : auto lastWrite = std::filesystem::last_write_time(filePath, ec);
824 16 : if (ec) {
825 8 : JAMI_WARNING("Unable to get last write time of {}: {}", filePath, ec.message());
826 2 : return 0;
827 : }
828 14 : return std::chrono::duration_cast<std::chrono::seconds>(lastWrite.time_since_epoch()).count();
829 : }
830 :
831 : } // namespace fileutils
832 : } // namespace jami
|