Fray Engine
Loading...
Searching...
No Matches
file_manager.hpp
Go to the documentation of this file.
1#ifndef FRAY_FILE_MANAGER_HPP
2#define FRAY_FILE_MANAGER_HPP
3
4#include <cstdlib>
5#include <cerrno>
6#include <cstdio>
7#include <ctime>
8#include <filesystem>
9#include <fstream>
10#include <memory>
11#include <set>
12#include <string>
13#include <system_error>
14#include <vector>
15
16#include <zip.h>
17
18#include "errors.hpp"
19#include "log_manager.hpp"
20
21#ifdef _WIN32
22#include <fcntl.h>
23#include <io.h>
24#include <share.h>
25#include <sys/stat.h>
26#ifndef NOMINMAX
27#define NOMINMAX
28#endif
29#ifndef WIN32_LEAN_AND_MEAN
30#define WIN32_LEAN_AND_MEAN
31#endif
32#include <windows.h>
33#else
34#include <fcntl.h>
35#include <sys/file.h>
36#include <sys/stat.h>
37#include <unistd.h>
38#ifdef __linux__
39#include <sys/syscall.h>
40#include <linux/fs.h>
41#endif
42#endif
43
44namespace fray { namespace state { class StateManager; } }
45namespace fray { class ProjectManager; }
46
47namespace fray
48{
49 namespace files
50 {
55 enum class ConflictChoice { Ask, Archive, Folder };
64
72 {
73 private:
79 std::filesystem::path _archive;
83 std::filesystem::path _workspace;
87 std::string _name;
91 std::string _databaseFile;
93 bool _existingDatabase = false;
97 bool _archiveExists = false;
101 bool _extracted = false;
106 {
107#ifdef _WIN32
111 HANDLE handle = INVALID_HANDLE_VALUE;
112#else
116 int handle = -1;
117#endif
121 std::filesystem::path path;
122 };
123
134 std::filesystem::path _conflictSource;
138 std::filesystem::path _conflictDestination;
142 std::string _conflictName;
146 bool _conflictFolder = false;
150 unsigned _users = 0;
154 std::shared_ptr<int> _lifetime = std::make_shared<int>(0);
155
161 static bool safeRelative(
162 const std::string& name)
163 {
164 if (name.empty() || name.find('\0') != std::string::npos ||
165 name.find('\\') != std::string::npos || name.find(':') != std::string::npos)
166 return false;
167 const std::filesystem::path path(name);
168 if (path.is_absolute() || path.has_root_name() || path.has_root_directory())
169 return false;
170 for (const auto& part : path)
171 if (part == "." || part == "..")
172 return false;
173 return true;
174 }
175
184 const std::filesystem::path& archive,
185 ProjectLock& lock)
186 {
187 auto lockPath = archive;
188 lockPath.replace_extension(".lock");
189#ifdef _WIN32
190 lock.handle = CreateFileW(lockPath.c_str(), GENERIC_READ | GENERIC_WRITE | DELETE, 0,
191 nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT,
192 nullptr);
193 if (lock.handle != INVALID_HANDLE_VALUE)
194 {
195 BY_HANDLE_FILE_INFORMATION info;
196 if (!GetFileInformationByHandle(lock.handle, &info) ||
197 (info.dwFileAttributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) ||
198 info.nFileSizeHigh != 0 || info.nFileSizeLow != 0)
199 {
200 CloseHandle(lock.handle);
201 lock.handle = INVALID_HANDLE_VALUE;
202 }
203 }
204 if (lock.handle == INVALID_HANDLE_VALUE)
205#else
206 lock.handle = ::open(lockPath.c_str(), O_CREAT | O_RDWR | O_NOFOLLOW, 0600);
207 if (lock.handle >= 0 && flock(lock.handle, LOCK_EX | LOCK_NB) != 0)
208 {
209 ::close(lock.handle);
210 lock.handle = -1;
211 }
212 if (lock.handle >= 0)
213 {
214 // A previous owner may have unlinked this inode before we acquired it.
215 struct stat descriptor, pathStatus;
216 if (fstat(lock.handle, &descriptor) != 0 || lstat(lockPath.c_str(), &pathStatus) != 0 ||
217 descriptor.st_dev != pathStatus.st_dev || descriptor.st_ino != pathStatus.st_ino ||
218 !S_ISREG(pathStatus.st_mode) || descriptor.st_size != 0)
219 {
220 ::close(lock.handle);
221 lock.handle = -1;
222 }
223 }
224 if (lock.handle < 0)
225#endif
226 {
227 fray::log::engineError("Cannot lock project: %s", lockPath.string().c_str());
228 return false;
229 }
230 lock.path = lockPath;
231 return true;
232 }
233
234#ifndef _WIN32
240 static bool lockIntact(
241 const ProjectLock& lock)
242 {
243 struct stat descriptor, pathStatus;
244 return lock.handle >= 0 && fstat(lock.handle, &descriptor) == 0 &&
245 lstat(lock.path.c_str(), &pathStatus) == 0 && descriptor.st_dev == pathStatus.st_dev &&
246 descriptor.st_ino == pathStatus.st_ino && S_ISREG(pathStatus.st_mode) &&
247 descriptor.st_size == 0;
248 }
249#endif
250
256 {
257#ifndef _WIN32
258 if (_lock.handle < 0 || _archive.empty() || lockIntact(_lock))
259 return;
260 ::close(_lock.handle);
261 _lock = ProjectLock();
263 fray::log::engineInfo("Project lock was missing and has been recreated.");
264#endif
265 }
266
273 static bool unlockProject(
274 ProjectLock& lock)
275 {
276#ifdef _WIN32
277 if (lock.handle == INVALID_HANDLE_VALUE)
278 return true;
279 FILE_DISPOSITION_INFO disposition = {TRUE};
280 if (!SetFileInformationByHandle(lock.handle, FileDispositionInfo, &disposition, sizeof(disposition)))
281 {
282 fray::log::engineError("Cannot remove project lock: %s", lock.path.string().c_str());
283 return false;
284 }
285 if (!CloseHandle(lock.handle))
286 {
287 fray::log::engineError("Cannot release project lock: %s", lock.path.string().c_str());
288 return false;
289 }
290 lock.handle = INVALID_HANDLE_VALUE;
291#else
292 if (lock.handle < 0)
293 return true;
294 // A lock that was renamed or deleted by the user is no longer ours to remove.
295 if (lockIntact(lock) && ::unlink(lock.path.c_str()) != 0)
296 {
297 fray::log::engineError("Cannot remove project lock: %s", lock.path.string().c_str());
298 return false;
299 }
300 ::close(lock.handle);
301 lock.handle = -1;
302#endif
303 lock.path.clear();
304 return true;
305 }
306
311 bool reset()
312 {
314 return false;
315 _archive.clear();
316 _workspace.clear();
317 _name.clear();
318 _databaseFile.clear();
319 _existingDatabase = false;
320 _archiveExists = false;
321 _extracted = false;
322 _conflictSource.clear();
323 _conflictDestination.clear();
324 _conflictName.clear();
325 return true;
326 }
327
333 {
334 if (_conflictSource.empty())
335 return true;
336 const bool databaseRestored = _conflictFolder
339 if (!databaseRestored)
340 {
341 fray::log::engineError("Cannot restore the unselected project's database name.");
342 return false;
343 }
345 {
346 const bool reverted = _conflictFolder
349 if (!reverted)
350 fray::log::engineError("Cannot restore the renamed project's database name.");
351 fray::log::engineError("Cannot restore the unselected project to %s.",
352 _conflictSource.string().c_str());
353 return false;
354 }
355 _conflictSource.clear();
356 _conflictDestination.clear();
357 _conflictName.clear();
358 return true;
359 }
360
366 {
368 return false;
369 _conflictSource.clear();
370 _conflictDestination.clear();
371 _conflictName.clear();
372 return true;
373 }
374
382 const std::string& stem)
383 {
384 const auto database = _workspace / (stem + ".sqlite");
385 bool exists;
386 if (!pathExists(database, exists))
387 return false;
388 if (!exists)
389 return true;
390 const std::time_t now = std::time(nullptr);
391 std::tm local{};
392#ifdef _WIN32
393 localtime_s(&local, &now);
394#else
395 localtime_r(&now, &local);
396#endif
397 char stamp[16];
398 std::strftime(stamp, sizeof(stamp), "%Y%m%d%H%M%S", &local);
399 const auto folder = _workspace / "snapshots";
400 std::error_code error;
401 std::filesystem::create_directory(folder, error);
402 if (error)
403 {
404 fray::log::engineError("Cannot create snapshots folder: %s", error.message().c_str());
405 return false;
406 }
407 auto target = folder / (stem + "-" + stamp + ".sqlite");
408 for (unsigned number = 1; ; ++number)
409 {
410 if (!pathExists(target, exists))
411 return false;
412 if (!exists)
413 break;
414 target = folder / (stem + "-" + stamp + "-" + std::to_string(number) + ".sqlite");
415 }
416 std::filesystem::copy_file(database, target, std::filesystem::copy_options::none, error);
417 if (error)
418 {
419 fray::log::engineError("Cannot snapshot project database: %s", error.message().c_str());
420 return false;
421 }
422 return true;
423 }
424
430 {
431 if (!_archiveExists)
432 return;
433 std::error_code error;
434 std::filesystem::remove(_archive, error);
435 if (error)
436 fray::log::engineError("Cannot remove %s while the project is open: %s",
437 _archive.string().c_str(), error.message().c_str());
438 else
439 _archiveExists = false;
440 }
441
450 const std::string& newName,
451 ProjectLock& lock)
452 {
453 restoreLock();
454 const auto newArchive = _archive.parent_path() / (newName + ".fry");
455 bool exists;
456 if (!pathExists(newArchive, exists))
457 return false;
458 if (exists)
459 {
460 fray::log::engineError("Cannot rename project: %s already exists.", newArchive.string().c_str());
461 return false;
462 }
463 return lockProject(newArchive, lock);
464 }
465
473 const std::string& newName,
474 const std::filesystem::path& workspace,
475 ProjectLock& lock)
476 {
477 ProjectLock previous = _lock;
478 _lock = lock;
479 lock = ProjectLock();
480 _name = newName;
481 _workspace = workspace;
482 _archive = _archive.parent_path() / (newName + ".fry");
483 if (!unlockProject(previous))
484 fray::log::engineError("The previous project lock could not be removed.");
485 }
486
493 static bool pathExists(
494 const std::filesystem::path& path,
495 bool& exists)
496 {
497 std::error_code error;
498 const auto status = std::filesystem::symlink_status(path, error);
499 if (error && error != std::errc::no_such_file_or_directory)
500 {
501 fray::log::engineError("Cannot inspect project path: %s", error.message().c_str());
502 return false;
503 }
504 exists = status.type() != std::filesystem::file_type::not_found;
505 return true;
506 }
507
515 static bool unusedPath(
516 const std::filesystem::path& parent,
517 const std::string& stem,
518 std::filesystem::path& output)
519 {
520 for (unsigned i = 1; i < 100000; ++i)
521 {
522 const auto candidate = parent / (stem + "-" + std::to_string(i));
523 bool folderExists, archiveExists;
524 if (!pathExists(candidate, folderExists) ||
525 !pathExists(candidate.string() + ".fry", archiveExists))
526 return false;
527 if (!folderExists && !archiveExists)
528 {
529 output = candidate;
530 return true;
531 }
532 }
533 fray::log::engineError("Cannot find an unused project path.");
534 return false;
535 }
536
543 static bool renameExclusive(
544 const std::filesystem::path& from,
545 const std::filesystem::path& to)
546 {
547#ifdef _WIN32
548 if (MoveFileW(from.c_str(), to.c_str()) != 0)
549 return true;
550 const std::error_code error(static_cast<int>(GetLastError()), std::system_category());
551#elif defined(__APPLE__)
552 if (::renamex_np(from.c_str(), to.c_str(), RENAME_EXCL) == 0)
553 return true;
554 const std::error_code error(errno, std::generic_category());
555#elif defined(__linux__)
556 if (::syscall(SYS_renameat2, AT_FDCWD, from.c_str(), AT_FDCWD, to.c_str(), RENAME_NOREPLACE) == 0)
557 return true;
558 const std::error_code error(errno, std::generic_category());
559#else
560 const std::error_code error = std::make_error_code(std::errc::operation_not_supported);
561#endif
562 fray::log::engineError("Cannot rename %s to %s: %s",
563 from.string().c_str(), to.string().c_str(), error.message().c_str());
564 return false;
565 }
566
576 const std::filesystem::path& folder,
577 const std::string& oldName,
578 const std::string& newName)
579 {
580 std::vector<std::pair<std::filesystem::path, std::filesystem::path>> renamed;
581 for (const char* suffix : {".sqlite", ".sqlite-wal", ".sqlite-shm", ".sqlite-journal"})
582 {
583 const auto from = folder / (oldName + suffix);
584 const auto to = folder / (newName + suffix);
585 bool exists, destinationExists;
586 if (!pathExists(from, exists) || !pathExists(to, destinationExists))
587 return false;
588 if (exists && destinationExists)
589 {
590 fray::log::engineError("Cannot rename project database: destination already exists: %s",
591 to.string().c_str());
592 return false;
593 }
594 if (exists)
595 renamed.emplace_back(from, to);
596 }
597 std::size_t completed = 0;
598 for (; completed < renamed.size(); ++completed)
599 {
600 if (!renameExclusive(renamed[completed].first, renamed[completed].second))
601 {
602 while (completed > 0)
603 {
604 --completed;
605 if (!renameExclusive(renamed[completed].second, renamed[completed].first))
606 fray::log::engineError("Could not restore a renamed project database file.");
607 }
608 return false;
609 }
610 }
611 return true;
612 }
613
623 const std::filesystem::path& path,
624 const std::string& oldName,
625 const std::string& newName)
626 {
627 int error = 0;
628 zip_t* archive = zip_open(path.string().c_str(), ZIP_CHECKCONS, &error);
629 if (!archive)
630 {
631 if (error == ZIP_ER_NOZIP || error == ZIP_ER_INCONS || error == ZIP_ER_EOF)
632 {
633 fray::log::engineInfo("Unselected file is not a readable ZIP; leaving its contents unchanged: %s",
634 path.string().c_str());
635 return true;
636 }
637 fray::log::engineError("Cannot open renamed project archive (zip error %d).", error);
638 return false;
639 }
640 bool changed = false;
641 for (const char* suffix : {".sqlite", ".sqlite-wal", ".sqlite-shm", ".sqlite-journal"})
642 {
643 const std::string from = oldName + suffix;
644 const std::string to = newName + suffix;
645 const zip_int64_t index = zip_name_locate(archive, from.c_str(), 0);
646 if (index < 0)
647 {
648 if (zip_error_code_zip(zip_get_error(archive)) == ZIP_ER_NOENT)
649 continue;
650 fray::log::engineError("Cannot inspect renamed project archive: %s", zip_strerror(archive));
651 zip_discard(archive);
652 return false;
653 }
654 if (zip_name_locate(archive, to.c_str(), 0) >= 0)
655 {
656 fray::log::engineError("Cannot rename archived project database: destination already exists: %s",
657 to.c_str());
658 zip_discard(archive);
659 return false;
660 }
661 if (zip_error_code_zip(zip_get_error(archive)) != ZIP_ER_NOENT)
662 {
663 fray::log::engineError("Cannot inspect renamed project archive: %s", zip_strerror(archive));
664 zip_discard(archive);
665 return false;
666 }
667 if (zip_file_rename(archive, static_cast<zip_uint64_t>(index),
668 to.c_str(), ZIP_FL_ENC_UTF_8) != 0)
669 {
670 fray::log::engineError("Cannot rename archived project database: %s", zip_strerror(archive));
671 zip_discard(archive);
672 return false;
673 }
674 changed = true;
675 }
676 if (!changed)
677 {
678 zip_discard(archive);
679 return true;
680 }
681 if (zip_close(archive) != 0)
682 {
683 fray::log::engineError("Cannot update renamed project archive: %s", zip_strerror(archive));
684 zip_discard(archive);
685 return false;
686 }
687 return true;
688 }
689
695 bool extract()
696 {
697 int error = 0;
698 zip_t* archive = zip_open(_archive.string().c_str(), ZIP_RDONLY | ZIP_CHECKCONS, &error);
699 if (!archive)
700 {
701 fray::log::engineError("Cannot open project archive (zip error %d).", error);
702 return false;
703 }
704 std::error_code fsError;
705 if (!std::filesystem::create_directory(_workspace, fsError))
706 {
707 fray::log::engineError("Cannot create project folder: %s", fsError.message().c_str());
708 zip_discard(archive);
709 return false;
710 }
711 bool ok = true;
712 std::set<std::string> paths;
713 const zip_int64_t entries = zip_get_num_entries(archive, 0);
714 if (entries < 0)
715 ok = false;
716 for (zip_uint64_t i = 0; ok && i < static_cast<zip_uint64_t>(entries); ++i)
717 {
718 const char* raw = zip_get_name(archive, i, 0);
719 const std::string name = raw == nullptr ? "" : raw;
720 zip_uint8_t system = 0;
721 zip_uint32_t attributes = 0;
722 if (!safeRelative(name) || !paths.insert(name).second ||
723 zip_file_get_external_attributes(archive, i, 0, &system, &attributes) != 0)
724 {
725 fray::log::engineError("Invalid project archive entry: %s", name.c_str());
726 ok = false;
727 break;
728 }
729 const unsigned type = system == ZIP_OPSYS_UNIX ? (attributes >> 16) & 0170000 : 0;
730 const bool directory = name.back() == '/';
731 if ((type != 0 && type != 0100000 && type != 0040000) ||
732 (type == 0040000 && !directory) || (type == 0100000 && directory))
733 {
734 fray::log::engineError("Unsupported project archive entry: %s", name.c_str());
735 ok = false;
736 break;
737 }
738 const auto destination = _workspace / std::filesystem::path(name);
739 if (directory)
740 {
741 std::filesystem::create_directories(destination, fsError);
742 ok = !fsError;
743 continue;
744 }
745 std::filesystem::create_directories(destination.parent_path(), fsError);
746 if (fsError || std::filesystem::exists(destination, fsError) || fsError)
747 {
748 fray::log::engineError("Cannot extract project entry: %s", name.c_str());
749 ok = false;
750 break;
751 }
752 zip_file_t* entry = zip_fopen_index(archive, i, 0);
753 if (!entry)
754 {
755 fray::log::engineError("Cannot read project entry: %s", name.c_str());
756 ok = false;
757 break;
758 }
759 std::ofstream output(destination, std::ios::binary | std::ios::trunc);
760 char buffer[65536];
761 zip_int64_t count = -1;
762 while (output && (count = zip_fread(entry, buffer, sizeof(buffer))) > 0)
763 output.write(buffer, count);
764 output.close();
765 const int closed = zip_fclose(entry);
766 if (count < 0 || !output || closed != 0)
767 {
768 fray::log::engineError("Cannot extract project entry: %s", name.c_str());
769 ok = false;
770 }
771 }
772 if (!ok && fsError)
773 fray::log::engineError("Cannot extract project: %s", fsError.message().c_str());
774 zip_discard(archive);
775 if (!ok)
776 {
777 std::filesystem::remove_all(_workspace, fsError);
778 if (fsError)
779 fray::log::engineError("Cannot remove incomplete project folder: %s", fsError.message().c_str());
780 }
781 return ok;
782 }
783
784 public:
788 FileManager() = default;
793 const FileManager&) = delete;
798 const FileManager&) = delete;
799
805 {
806 if (_users != 0)
807 fray::log::engineError("File manager destroyed while state managers are still using it.");
808 _lifetime.reset();
809 if (!reset())
810 {
811#ifdef _WIN32
812 if (_extraLock.handle != INVALID_HANDLE_VALUE)
813 CloseHandle(_extraLock.handle);
814 if (_lock.handle != INVALID_HANDLE_VALUE)
815 CloseHandle(_lock.handle);
816#else
817 if (_extraLock.handle >= 0)
818 ::close(_extraLock.handle);
819 if (_lock.handle >= 0)
820 ::close(_lock.handle);
821#endif
822 }
823 }
824
828 bool isOpen() const { return !_workspace.empty(); }
832 const std::string& projectName() const { return _name; }
837 std::string databaseFileName() const
838 {
839 return _databaseFile.empty() ? _name + ".sqlite" : _databaseFile;
840 }
841
849 const std::filesystem::path& workingDirectory() const { return _workspace; }
853 const std::filesystem::path& archivePath() const { return _archive; }
854
862 const std::filesystem::path& directory,
863 const std::string& name)
864 {
865 if (isOpen() || !_lock.path.empty() || !_extraLock.path.empty() ||
866 directory.empty() || directory.string().find('\0') != std::string::npos ||
867 !safeRelative(name) || name.find('/') != std::string::npos)
868 {
869 fray::log::engineError("Cannot open state directory: invalid directory or database name.");
870 return fray::errors::FAILED_OPEN_PROJECT;
871 }
872 std::error_code error;
873 const auto resolved = std::filesystem::canonical(directory, error);
874 if (error || !std::filesystem::is_directory(resolved, error) || error)
875 {
876 fray::log::engineError("Cannot open state directory: %s", directory.string().c_str());
877 return fray::errors::FAILED_OPEN_PROJECT;
878 }
879 if (!lockProject(resolved / (name + ".sqlite.lock"), _lock))
880 return fray::errors::FAILED_OPEN_PROJECT;
881 _workspace = resolved;
882 _name = name;
883 _databaseFile = name + ".sqlite";
884 return fray::errors::NONE;
885 }
886
893 const std::filesystem::path& path)
894 {
895 if (isOpen() || !_lock.path.empty() || !_extraLock.path.empty() ||
896 path.empty() || path.string().find('\0') != std::string::npos ||
897 !safeRelative(path.filename().string()))
898 {
899 fray::log::engineError("Cannot open database file: invalid path or files already open.");
900 return fray::errors::FAILED_OPEN_PROJECT;
901 }
902 std::error_code error;
903 const auto status = std::filesystem::symlink_status(path, error);
904 if (error || !std::filesystem::is_regular_file(status))
905 {
906 fray::log::engineError("Cannot open database file: not an existing regular file.");
907 return fray::errors::FAILED_OPEN_PROJECT;
908 }
909 const auto parent = std::filesystem::canonical(
910 path.parent_path().empty() ? std::filesystem::path(".") : path.parent_path(), error);
911 if (error || !std::filesystem::is_directory(parent, error) || error)
912 {
913 fray::log::engineError("Cannot open database file: invalid parent directory.");
914 return fray::errors::FAILED_OPEN_PROJECT;
915 }
916 const auto filename = path.filename().string();
917 if (!lockProject(parent / (filename + ".lock"), _lock))
918 return fray::errors::FAILED_OPEN_PROJECT;
919 _workspace = parent;
920 _name = path.stem().string();
921 _databaseFile = filename;
922 _existingDatabase = true;
923 return fray::errors::NONE;
924 }
925
933 const std::string& name,
934 std::filesystem::path& result) const
935 {
936 if (!isOpen() || !safeRelative(name))
937 {
938 fray::log::engineError("Cannot access project file: project is closed or path is invalid.");
939 return fray::errors::FAILED_OPEN_PROJECT;
940 }
941 std::filesystem::path current = _workspace;
942 for (const auto& part : std::filesystem::path(name))
943 {
944 current /= part;
945 std::error_code error;
946 const auto status = std::filesystem::symlink_status(current, error);
947 if ((error && error != std::errc::no_such_file_or_directory) ||
948 std::filesystem::is_symlink(status))
949 {
950 fray::log::engineError("Cannot access project file: invalid or symbolic-link path.");
951 return fray::errors::FAILED_OPEN_PROJECT;
952 }
953 }
954 result = current;
955 return fray::errors::NONE;
956 }
957
971 const std::string& path,
974 bool deferConflictCommit = false)
975 {
976 if (isOpen() || !_lock.path.empty() || !_extraLock.path.empty() ||
977 path.empty() || path.find('\0') != std::string::npos)
978 {
979 fray::log::engineError("Cannot open project: invalid path or project already open.");
980 return fray::errors::FAILED_OPEN_PROJECT;
981 }
982 std::error_code error;
983 auto input = std::filesystem::weakly_canonical(path, error);
984 if (error)
985 {
986 fray::log::engineError("Cannot resolve project path: %s", error.message().c_str());
987 return fray::errors::FAILED_OPEN_PROJECT;
988 }
989 if (input.filename().empty() && input != input.root_path())
990 input = input.parent_path();
991 const bool inputArchive = input.extension() == ".fry";
992 _name = inputArchive ? input.stem().string() : input.filename().string();
993 if (_name.empty() || _name == "." || _name == "..")
994 {
995 fray::log::engineError("Cannot open project: invalid project name.");
996 reset();
997 return fray::errors::FAILED_OPEN_PROJECT;
998 }
999 const auto parent = input.parent_path();
1000 const auto originalArchive = inputArchive ? input : parent / (_name + ".fry");
1001 const auto originalFolder = inputArchive ? parent / _name : input;
1002 bool hasArchive = std::filesystem::exists(originalArchive, error);
1003 if (error)
1004 {
1005 fray::log::engineError("Cannot inspect project archive: %s", error.message().c_str());
1006 reset();
1007 return fray::errors::FAILED_OPEN_PROJECT;
1008 }
1009 bool hasFolder = std::filesystem::exists(originalFolder, error);
1010 if (error || (hasFolder && !std::filesystem::is_directory(originalFolder, error)))
1011 {
1012 fray::log::engineError("Cannot inspect project folder: %s", error.message().c_str());
1013 reset();
1014 return fray::errors::FAILED_OPEN_PROJECT;
1015 }
1016 if (hasFolder && std::filesystem::is_symlink(std::filesystem::symlink_status(originalFolder, error)))
1017 {
1018 fray::log::engineError("Cannot open a symbolic-link project folder.");
1019 reset();
1020 return fray::errors::FAILED_OPEN_PROJECT;
1021 }
1022 if (error)
1023 {
1024 fray::log::engineError("Cannot inspect project folder: %s", error.message().c_str());
1025 reset();
1026 return fray::errors::FAILED_OPEN_PROJECT;
1027 }
1028 if (hasArchive && hasFolder &&
1029 ((choice == ConflictChoice::Ask && mode != OpenMode::CreateNew) ||
1031 {
1032 reset();
1033 return fray::errors::PROJECT_CONFLICT;
1034 }
1035 if (!lockProject(originalArchive, _lock))
1036 {
1037 reset();
1038 return fray::errors::FAILED_OPEN_PROJECT;
1039 }
1040 hasArchive = std::filesystem::exists(originalArchive, error);
1041 if (!error)
1042 hasFolder = std::filesystem::exists(originalFolder, error);
1043 if (error)
1044 {
1045 fray::log::engineError("Cannot inspect project after locking: %s", error.message().c_str());
1046 reset();
1047 return fray::errors::FAILED_OPEN_PROJECT;
1048 }
1049 if (mode == OpenMode::CreateNew && (hasArchive || hasFolder))
1050 {
1051 const F_err result = hasArchive && hasFolder ? errors::PROJECT_BOTH_EXIST :
1052 hasArchive ? errors::PROJECT_ARCHIVE_EXISTS : errors::PROJECT_FOLDER_EXISTS;
1053 reset();
1054 return result;
1055 }
1056 if ((mode == OpenMode::OpenExisting || mode == OpenMode::OpenSelected) &&
1057 ((!hasFolder && !hasArchive) ||
1058 (choice == ConflictChoice::Archive && !hasArchive) ||
1059 (choice == ConflictChoice::Folder && !hasFolder)))
1060 {
1061 reset();
1062 return errors::PROJECT_NOT_FOUND;
1063 }
1064 if ((mode == OpenMode::CreateInFolder || mode == OpenMode::CreateInFolderResolve) && !hasFolder)
1065 {
1066 reset();
1067 return errors::PROJECT_NOT_FOUND;
1068 }
1069 if (hasArchive && hasFolder &&
1070 (choice == ConflictChoice::Ask || mode == OpenMode::OpenSelected ||
1071 mode == OpenMode::CreateInFolder))
1072 {
1073 reset();
1074 return fray::errors::PROJECT_CONFLICT;
1075 }
1076 const bool useArchive = hasArchive && (!hasFolder || choice == ConflictChoice::Archive);
1077 _archive = originalArchive;
1078 _archiveExists = hasArchive;
1079 _workspace = originalFolder;
1080 if (hasArchive && hasFolder)
1081 {
1082 std::filesystem::path extra;
1083 if (!unusedPath(parent, _name + "-unselected", extra) ||
1084 !lockProject(extra.string() + ".fry", _extraLock))
1085 {
1086 reset();
1087 return fray::errors::FAILED_OPEN_PROJECT;
1088 }
1089 const std::string newName = extra.filename().string();
1090 const auto source = useArchive ? originalFolder : originalArchive;
1091 const std::filesystem::path destination = useArchive
1092 ? extra : std::filesystem::path(extra.string() + ".fry");
1093 bool folderExists, archiveExists;
1094 if (!pathExists(extra, folderExists) ||
1095 !pathExists(extra.string() + ".fry", archiveExists) ||
1096 folderExists || archiveExists || !renameExclusive(source, destination))
1097 {
1098 fray::log::engineError("Cannot resolve project naming conflict.");
1099 reset();
1100 return fray::errors::FAILED_OPEN_PROJECT;
1101 }
1102 const bool renamedDatabase = useArchive
1103 ? renameFolderDatabase(destination, _name, newName)
1104 : renameArchiveDatabase(destination, _name, newName);
1105 if (!renamedDatabase)
1106 {
1107 if (!renameExclusive(destination, source))
1108 fray::log::engineError("Could not restore the original project path after rename failed.");
1109 reset();
1110 return fray::errors::FAILED_OPEN_PROJECT;
1111 }
1112 fray::log::engineInfo("Renamed %s to %s", source.string().c_str(),
1113 destination.string().c_str());
1114 _conflictSource = source;
1115 _conflictDestination = destination;
1116 _conflictName = newName;
1117 _conflictFolder = useArchive;
1118 if (!deferConflictCommit && !commitConflict())
1119 {
1121 reset();
1122 return fray::errors::FAILED_OPEN_PROJECT;
1123 }
1124 if (useArchive)
1125 hasFolder = false;
1126 else
1127 _archiveExists = false;
1128 }
1129 if (useArchive)
1130 {
1131 if (!extract())
1132 {
1134 reset();
1135 return fray::errors::FAILED_OPEN_PROJECT;
1136 }
1137 _extracted = true;
1138 }
1139 else if (!hasFolder && !std::filesystem::create_directory(_workspace, error))
1140 {
1141 fray::log::engineError("Cannot create project folder: %s", error.message().c_str());
1142 reset();
1143 return fray::errors::FAILED_OPEN_PROJECT;
1144 }
1145 return fray::errors::NONE;
1146 }
1147
1154 {
1155 if (!isOpen() || _archive.empty() || _users != 0)
1156 {
1157 fray::log::engineError("Cannot archive project: project is closed or state is still open.");
1158 return fray::errors::FAILED_SAVE_PROJECT;
1159 }
1160 int error = 0;
1161 zip_t* archive = zip_open(_archive.string().c_str(),
1162 _archiveExists ? ZIP_TRUNCATE : ZIP_CREATE | ZIP_EXCL, &error);
1163 if (!archive)
1164 {
1165 fray::log::engineError("Cannot create project archive (zip error %d).", error);
1166 return fray::errors::FAILED_SAVE_PROJECT;
1167 }
1168 std::error_code fsError;
1169 std::filesystem::recursive_directory_iterator it(_workspace, fsError), end;
1170 bool ok = !fsError;
1171 for (; ok && it != end; it.increment(fsError))
1172 {
1173 if (fsError)
1174 {
1175 ok = false;
1176 break;
1177 }
1178 const auto status = it->symlink_status(fsError);
1179 if (fsError || (!std::filesystem::is_regular_file(status) && !std::filesystem::is_directory(status)))
1180 {
1181 fray::log::engineError("Cannot archive unsupported project file: %s", it->path().string().c_str());
1182 ok = false;
1183 break;
1184 }
1185 const std::string name = it->path().lexically_relative(_workspace).generic_string();
1186 if (!safeRelative(name))
1187 {
1188 fray::log::engineError("Cannot archive invalid project path: %s", name.c_str());
1189 ok = false;
1190 break;
1191 }
1192 if (std::filesystem::is_directory(status))
1193 ok = zip_dir_add(archive, (name + "/").c_str(), ZIP_FL_ENC_UTF_8) >= 0;
1194 else
1195 {
1196 const std::string path = it->path().string();
1197 zip_source_t* source = zip_source_file(archive, path.c_str(), 0, -1);
1198 if (!source)
1199 ok = false;
1200 else if (zip_file_add(archive, name.c_str(), source, ZIP_FL_ENC_UTF_8) < 0)
1201 {
1202 zip_source_free(source);
1203 ok = false;
1204 }
1205 }
1206 }
1207 if (fsError)
1208 ok = false;
1209 if (!ok)
1210 {
1211 fray::log::engineError("Cannot archive project: %s",
1212 fsError ? fsError.message().c_str() : zip_strerror(archive));
1213 zip_discard(archive);
1214 return fray::errors::FAILED_SAVE_PROJECT;
1215 }
1216 if (zip_close(archive) != 0)
1217 {
1218 fray::log::engineError("Cannot save project archive: %s", zip_strerror(archive));
1219 zip_discard(archive);
1220 return fray::errors::FAILED_SAVE_PROJECT;
1221 }
1222 _archiveExists = true;
1223 return fray::errors::NONE;
1224 }
1225
1232 {
1233 if (!isOpen() || _users != 0)
1234 {
1235 fray::log::engineError("Cannot close project: project is closed or state is still open.");
1236 return fray::errors::FAILED_CLOSE_PROJECT;
1237 }
1238 return reset() ? fray::errors::NONE : fray::errors::FAILED_CLOSE_PROJECT;
1239 }
1240
1241 private:
1248 {
1249 if (!isOpen() || _users != 0)
1250 {
1251 fray::log::engineError("Cannot remove project folder: project is closed or state is still open.");
1252 return fray::errors::FAILED_CLOSE_PROJECT;
1253 }
1254 std::error_code error;
1255 // Tests whether parent is a component-wise prefix of child.
1256 const auto contains = [](const std::filesystem::path& parent, const std::filesystem::path& child)
1257 {
1258 auto part = parent.begin();
1259 auto other = child.begin();
1260 for (; part != parent.end() && other != child.end(); ++part, ++other)
1261 if (*part != *other)
1262 return false;
1263 return part == parent.end();
1264 };
1265 const auto cwd = std::filesystem::current_path(error);
1266 if (error)
1267 {
1268 fray::log::engineError("Cannot check project folder safety: %s", error.message().c_str());
1269 return fray::errors::FAILED_CLOSE_PROJECT;
1270 }
1271 const auto current = std::filesystem::weakly_canonical(cwd, error);
1272 if (error)
1273 {
1274 fray::log::engineError("Cannot check project folder safety: %s", error.message().c_str());
1275 return fray::errors::FAILED_CLOSE_PROJECT;
1276 }
1277 bool protectedFolder = _workspace == _workspace.root_path() || contains(_workspace, current);
1278 const char* home = std::getenv("HOME");
1279#ifdef _WIN32
1280 if (home == nullptr || *home == '\0')
1281 home = std::getenv("USERPROFILE");
1282#endif
1283 if (home != nullptr && *home != '\0')
1284 {
1285 const auto homePath = std::filesystem::weakly_canonical(home, error);
1286 if (error)
1287 {
1288 fray::log::engineError("Cannot check home directory safety: %s", error.message().c_str());
1289 return fray::errors::FAILED_CLOSE_PROJECT;
1290 }
1291 protectedFolder = protectedFolder || contains(_workspace, homePath);
1292 }
1293 if (protectedFolder)
1294 {
1295 fray::log::engineError("Project was archived, but the protected working folder was not removed: %s",
1296 _workspace.string().c_str());
1297 return fray::errors::FAILED_CLOSE_PROJECT;
1298 }
1299 std::filesystem::remove_all(_workspace, error);
1300 if (error)
1301 {
1302 fray::log::engineError("Project was archived, but its working folder could not be removed: %s (%s)",
1303 _workspace.string().c_str(), error.message().c_str());
1304 return fray::errors::FAILED_CLOSE_PROJECT;
1305 }
1306 return fray::errors::NONE;
1307 }
1308
1312 void attach() { ++_users; }
1316 void detach() { --_users; }
1320 std::weak_ptr<int> lifetime() const { return _lifetime; }
1321 };
1322 }
1323}
1324
1325#endif
Owns a project’s files, state stores, watcher and registered threads. Public operations synchronize t...
std::shared_ptr< int > _lifetime
Lifetime sentinel observed weakly by attached state managers.
bool isOpen() const
Returns whether a working directory is associated with this manager.
static bool safeRelative(const std::string &name)
Checks whether a project entry name is a safe relative path.
void commitRename(const std::string &newName, const std::filesystem::path &workspace, ProjectLock &lock)
Transfers a new lock and updates the project name and paths, then releases the old lock.
void removeArchive()
Removes the existing archive while the project is open, logging any failure. A later save recreates t...
bool _archiveExists
Whether the archive is expected to exist.
void restoreLock()
Attempts to recreate the primary lock if its file was renamed or removed. On POSIX,...
ProjectLock _extraLock
Temporary lock for the renamed, unselected conflict representation.
std::filesystem::path _workspace
Working folder path; empty when no project is open.
F_err save()
Packages the workspace into its .fry archive without deleting the workspace. Requires an open project...
bool reset()
Releases both locks and clears the current project and conflict paths.
std::filesystem::path _archive
Path of the project archive associated with the workspace.
std::weak_ptr< int > lifetime() const
Returns a weak lifetime sentinel that expires when this manager is destroyed.
ProjectLock _lock
Lock for the selected project archive path.
static bool unlockProject(ProjectLock &lock)
Removes and releases an owned project lock. On POSIX, only unlinks the path if it still identifies th...
std::filesystem::path _conflictDestination
Renamed path of the unselected representation awaiting resolution.
static bool renameExclusive(const std::filesystem::path &from, const std::filesystem::path &to)
Renames a filesystem entry without replacing an existing destination.
bool lockProject(const std::filesystem::path &archive, ProjectLock &lock)
Acquires a nonblocking exclusive lock on the archive path’s .lock file. Creates the lock file if need...
const std::filesystem::path & archivePath() const
Returns a borrowed reference to the archive path.
const std::string & projectName() const
Returns a borrowed reference to the current project or database name.
void detach()
Unregisters an attached state manager; requires a prior unmatched attach().
bool acquireRename(const std::string &newName, ProjectLock &lock)
Locks the proposed archive path after checking that the archive does not exist. Attempts to restore t...
void attach()
Registers an attached state manager; callers must balance this with detach().
static bool pathExists(const std::filesystem::path &path, bool &exists)
Inspects a path without following its final symbolic link.
bool extract()
Extracts the archive into a newly created workspace, rejecting unsafe or unsupported entries....
std::string _name
Current project name and database stem.
std::string _databaseFile
Explicit database filename for a directory-backed store; empty for a project.
static bool lockIntact(const ProjectLock &lock)
Checks that a POSIX lock descriptor still names the same empty regular file as its path.
FileManager & operator=(const FileManager &)=delete
Copy assignment is disabled; project locks have a single owner.
bool _extracted
Whether the workspace was extracted from an archive.
std::string databaseFileName() const
Returns the database filename within the open directory.
F_err filePath(const std::string &name, std::filesystem::path &result) const
Resolves a safe relative project path without accepting symbolic-link components.
bool rollbackConflict()
Attempts to restore an unselected conflict representation and its database names.
unsigned _users
Number of attached state managers; nonzero prevents save and close.
std::filesystem::path _conflictSource
Original path of an unselected representation awaiting conflict commit or rollback.
F_err removeWorkingDirectory()
Deletes the workspace tree after checking it does not contain protected locations....
F_err openDatabase(const std::filesystem::path &path)
Opens an existing named database file without treating its directory as a project.
bool requiresExistingDatabase() const
Reports whether state opens must require an existing database.
~FileManager()
Invalidates the lifetime sentinel and releases project locks. Logs if state managers remain attached;...
static bool renameFolderDatabase(const std::filesystem::path &folder, const std::string &oldName, const std::string &newName)
Renames a folder’s database and SQLite sidecars without overwriting destinations. Attempts to reverse...
bool commitConflict()
Finalizes a conflict rename by releasing its extra lock and clearing rollback state.
bool snapshotDatabase(const std::string &stem)
Copies an existing workspace database into snapshots with a timestamp and collision suffix....
F_err open(const std::string &path, ConflictChoice choice=ConflictChoice::Ask, OpenMode mode=OpenMode::OpenOrCreate, bool deferConflictCommit=false)
Opens or creates a project workspace and acquires its nonblocking project lock. May extract an archiv...
bool _existingDatabase
Whether opening state must not create a missing database file.
static bool unusedPath(const std::filesystem::path &parent, const std::string &stem, std::filesystem::path &output)
Finds an unused numbered folder name with no matching .fry archive.
const std::filesystem::path & workingDirectory() const
Returns a borrowed reference to the working folder path.
F_err close()
Releases locks and forgets the open project without saving or deleting its workspace....
std::string _conflictName
New database stem of the unselected representation.
static bool renameArchiveDatabase(const std::filesystem::path &path, const std::string &oldName, const std::string &newName)
Renames database and SQLite sidecar entries within an archive. Unreadable non-ZIP,...
FileManager(const FileManager &)=delete
Copy construction is disabled; project locks have a single owner.
bool _conflictFolder
Whether the unselected representation is a folder rather than an archive.
FileManager()=default
Constructs a closed file manager.
F_err openDirectory(const std::filesystem::path &directory, const std::string &name)
Opens an existing directory for a named state database without project archive operations.
Owns a SQLite connection and a typed key/value state table. Database operations serialize on a recurs...
F_long F_err
Error return type used across the Engine; the value is a fray::errors::code (0 / NONE means success).
Definition errors.hpp:13
ConflictChoice
Selects how an archive/folder name conflict is resolved. Ask reports a conflict; Archive selects the ...
OpenMode
Selects existence and conflict requirements when opening a project. OpenOrCreate opens or creates; Cr...
F_void engineInfo(const F_char *fmt,...)
Log info for Engine.
F_void engineError(const F_char *fmt,...)
Log error for Engine.
Owns the operating-system handle and path of a project lock file.
std::filesystem::path path
Path of the locked file.
int handle
Open locked file descriptor, or -1.