mirror of
https://github.com/veracrypt/VeraCrypt.git
synced 2026-10-05 16:46:35 -05:00
macOS: harden volume discovery and FUSE-T teardown
Run display discovery asynchronously and bound batched disk-image inventory queries. Filter auxiliary mounts by basename, filesystem and owner, and keep unresolved candidates separate from verified volumes. Allow targeted dismounts despite incomplete discovery while requiring complete results for slot allocation and empty-inventory decisions. Use nonthrowing GUI snapshots with monotonic freshness, completion events and safe window lifetimes. Suspend inactivity decisions while the snapshot is stale, without restarting idle timers: activity counters are cumulative per volume instance. Refresh logout targets and retry only failed ones. Show a progress dialog for interactive unmounts, but keep automatic ones synchronous, so a quit or logout request that arrives meanwhile is handled afterwards rather than refused. Guard core operations against reentry and route wait-dialog requests only from worker threads, so a main-thread message cannot wait for itself. Bind teardown to captured mount and service identities, including process start time. Report a service exit that cannot be confirmed after auxiliary mount removal as a distinct error that keeps the original details. Such volumes are not retried, and a multi-volume unmount reports all of them together with any other failure or a declined prompt. Warn about it after automatic unmounts and at quit, and keep the background application until the warning is acknowledged. Keep rollback responsive, and let services remove their auxiliary directories without probing mounted paths. Preserve released /control compatibility and perform best-effort cleanup for older services. Reap bounded subprocesses as soon as their output ends. A child that survives SIGKILL is reaped by a later call, which starts no new child until then. Keep subjects and subprocess command, status and error output when formatting exceptions for wrapping and logs. Clarify discovery and rollback diagnostics. Fix the localization-dependent busy-volume regression assertion and extend discovery, snapshot, process identity, cleanup, GUI lifecycle, inactivity and teardown coverage.
This commit is contained in:
38 files changed
+2551
-311
No files matched your search
+12
-2
@@ -1691,8 +1691,18 @@
|
||||
<entry lang="en" key="SYSENC_EFI_LOADER_NOT_TRUSTED_BY_SECUREBOOT">Warning: VeraCrypt could not validate the installed EFI bootloader files against one complete embedded resource set and confirm that all known required signing CAs are present in db and not listed by dbx. Firmware may reject VeraCrypt when Secure Boot is enabled.\n\nBefore booting with Secure Boot enabled, restore the required Microsoft certificates and current dbx as needed, then run VeraCrypt Repair/Reinstall. Do not remove Microsoft Corporation UEFI CA 2011 until db contains both Microsoft UEFI CA 2023 and Microsoft Option ROM UEFI CA 2023 and the actual installed files match VeraCrypt's 2023 set. This check cannot model every image-hash or security-version revocation. Make sure you have an up-to-date VeraCrypt Rescue Disk.</entry>
|
||||
<entry lang="en" key="SYSENC_EFI_WINDOWS_LOADER_NOT_TRUSTED_BY_SECUREBOOT">Warning: VeraCrypt could not validate the embedded signature and known-CA compatibility of the Windows Boot Manager it chainloads (bootmgfw_ms.vc). The file may be missing, unreadable, not a Windows Boot Manager, have an unrecognized embedded signer, or use a known signing CA that is absent from db or listed by dbx. The handoff to Windows may fail when Secure Boot is enabled.\n\nComplete or repair the Windows Secure Boot certificate and boot-manager update, keep the VeraCrypt System Favorites service enabled, and run VeraCrypt Repair/Reinstall. Repair also checks Windows' serviced EFI_EX/EFI copies for a compatible current Boot Manager. If Windows cannot start, temporarily disable Secure Boot to recover. Make sure you have an up-to-date VeraCrypt Rescue Disk.</entry>
|
||||
<entry lang="en" key="SYSENC_EFI_WINDOWS_LOADER_PCA2011_MIGRATION_NEEDED">Warning: The embedded signature of the Windows Boot Manager used by VeraCrypt (bootmgfw_ms.vc) is still issued by Microsoft Windows Production PCA 2011, although firmware db already contains Windows UEFI CA 2023. Its known CA is currently allowed, but it will no longer start after the PCA 2011 certificate is added to dbx.\n\nDo not apply the PCA 2011 revocation (AvailableUpdates bit 0x80, including combined value 0x280) yet. First complete the Windows 2023 boot-manager update while the VeraCrypt System Favorites service is enabled, then run VeraCrypt Repair/Reinstall so VeraCrypt can import a compatible serviced EFI_EX/EFI copy. Verify the embedded issuer of bootmgfw_ms.vc is Windows UEFI CA 2023 and make sure you have an up-to-date VeraCrypt Rescue Disk.</entry>
|
||||
<entry lang="en" key="MOUNT_SERVICE_INCOMPATIBLE">The service running this volume does not support the requested dismount operation.\n\nDismount the volume using the version of VeraCrypt that mounted it, then mount it again with this version. Close files using the volume if necessary. Always dismount volumes before upgrading VeraCrypt.</entry>
|
||||
<entry lang="en" key="MOUNT_SERVICE_CLEANUP_FAILED">VeraCrypt could not complete cleanup after a failed mount. The volume may still be accessible.\n\nDismount the volume in VeraCrypt. If dismounting fails, restart the computer before relying on the volume being locked.</entry>
|
||||
<entry lang="en" key="MOUNT_SERVICE_INCOMPATIBLE">The service running this volume does not support the requested unmount operation.\n\nUnmount the volume using the version of VeraCrypt that mounted it, then mount it again with this version. Close files using the volume if necessary. Always unmount volumes before upgrading VeraCrypt.</entry>
|
||||
<entry lang="en" key="MOUNT_SERVICE_CLEANUP_FAILED">VeraCrypt could not complete cleanup after a failed mount. The volume may still be accessible.\n\nUnmount the volume in VeraCrypt. If unmounting fails, restart the computer before relying on the volume being locked.</entry>
|
||||
<entry lang="en" key="DISMOUNT_SERVICE_CLEANUP_FAILED">The volume's auxiliary mount has been removed, but VeraCrypt could not confirm that its service has stopped. Encryption keys may still be in memory.\n\nIf the service does not stop, restart the computer before relying on the volume being locked.</entry>
|
||||
<entry lang="en" key="MOUNT_SERVICE_UNAVAILABLE">VeraCrypt could not contact or verify the volume service.\n\nIf this occurred while dismounting, close files using the volume and retry. If cleanup cannot be confirmed, restart the computer before relying on the volume being locked.</entry>
|
||||
<entry lang="en" key="VOLUME_DISCOVERY_FAILED">VeraCrypt could not verify all volume information. A volume service or disk image may be unavailable or inaccessible.\n\nAny volumes shown are only the entries VeraCrypt could verify. Wait for pending disk operations to finish and retry. An incomplete list does not confirm that all volumes are dismounted.</entry>
|
||||
<entry lang="en" key="VOLUME_IN_USE">The volume is in use. Close files and applications using it, then retry unmounting.</entry>
|
||||
<entry lang="en" key="OPERATION_TIMED_OUT">The operation did not finish in time. Check the volume's status before retrying.</entry>
|
||||
<entry lang="en" key="VOLUME_STATUS_UNKNOWN">Status unavailable</entry>
|
||||
<entry lang="en" key="VOLUME_IMAGE_ABSENT">Image detached; unmount to finish</entry>
|
||||
<entry lang="en" key="VOLUME_DISCOVERY_PENDING">Refreshing volume status…</entry>
|
||||
<entry lang="en" key="VOLUME_DISCOVERY_STALLED">Volume status unavailable; retrying…</entry>
|
||||
<entry lang="en" key="VOLUME_DISCOVERY_PARTIAL">Some volume information is unavailable; retrying…</entry>
|
||||
</localization>
|
||||
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
|
||||
<xs:element name="VeraCrypt">
|
||||
|
||||
@@ -218,21 +218,22 @@ namespace VeraCrypt
|
||||
|
||||
shared_ptr <VolumeInfo> CoreBase::GetMountedVolume (const VolumePath &volumePath) const
|
||||
{
|
||||
VolumeInfoList volumes = GetMountedVolumes (volumePath);
|
||||
if (volumes.empty())
|
||||
return shared_ptr <VolumeInfo> ();
|
||||
else
|
||||
return volumes.front();
|
||||
VolumeDiscoveryResult result = GetMountedVolumesWithStatus (volumePath);
|
||||
if (!result.Volumes.empty()) return result.Volumes.front();
|
||||
if (!result.IsComplete()) throw VolumeDiscoveryFailed (SRC_POS, wstring (result.UnresolvedMounts.front()));
|
||||
return shared_ptr <VolumeInfo> ();
|
||||
}
|
||||
|
||||
shared_ptr <VolumeInfo> CoreBase::GetMountedVolume (VolumeSlotNumber slot) const
|
||||
{
|
||||
foreach (shared_ptr <VolumeInfo> volume, GetMountedVolumes())
|
||||
VolumeDiscoveryResult result = GetMountedVolumesWithStatus();
|
||||
foreach (shared_ptr <VolumeInfo> volume, result.Volumes)
|
||||
{
|
||||
if (volume->SlotNumber == slot)
|
||||
return volume;
|
||||
}
|
||||
|
||||
if (!result.IsComplete()) throw VolumeDiscoveryFailed (SRC_POS, wstring (result.UnresolvedMounts.front()));
|
||||
return shared_ptr <VolumeInfo> ();
|
||||
}
|
||||
|
||||
|
||||
@@ -58,6 +58,12 @@ namespace VeraCrypt
|
||||
virtual shared_ptr <VolumeInfo> GetMountedVolume (const VolumePath &volumePath) const;
|
||||
virtual shared_ptr <VolumeInfo> GetMountedVolume (VolumeSlotNumber slot) const;
|
||||
virtual VolumeInfoList GetMountedVolumes (const VolumePath &volumePath = VolumePath()) const = 0;
|
||||
virtual VolumeDiscoveryResult GetMountedVolumesWithStatus (const VolumePath &volumePath = VolumePath()) const
|
||||
{
|
||||
VolumeDiscoveryResult result;
|
||||
result.Volumes = GetMountedVolumes (volumePath);
|
||||
return result;
|
||||
}
|
||||
virtual bool HasAdminPrivileges () const = 0;
|
||||
virtual void Init () { }
|
||||
virtual bool IsDeviceChangeInProgress () const { return DeviceChangeInProgress; }
|
||||
|
||||
@@ -55,6 +55,9 @@ namespace VeraCrypt
|
||||
TC_EXCEPTION (MountPointUnavailable); \
|
||||
TC_EXCEPTION (MountServiceIncompatible); \
|
||||
TC_EXCEPTION (MountServiceCleanupFailed); \
|
||||
TC_EXCEPTION (DismountServiceCleanupFailed); \
|
||||
TC_EXCEPTION (MountServiceUnavailable); \
|
||||
TC_EXCEPTION (VolumeDiscoveryFailed); \
|
||||
TC_EXCEPTION (NoDriveLetterAvailable); \
|
||||
TC_EXCEPTION (TemporaryDirectoryFailure); \
|
||||
TC_EXCEPTION (UnsupportedSectorSizeHiddenVolumeProtection); \
|
||||
|
||||
+141
-85
@@ -78,11 +78,15 @@ namespace VeraCrypt
|
||||
|
||||
CoreUnix::CoreUnix ()
|
||||
{
|
||||
signal (SIGPIPE, SIG_IGN);
|
||||
|
||||
char *loc = setlocale (LC_ALL, "");
|
||||
if (!loc || string (loc) == "C")
|
||||
setlocale (LC_ALL, "en_US.UTF-8");
|
||||
// Additional read-only core instances may be created for GUI discovery.
|
||||
// Locale and signal disposition are process state, not instance state.
|
||||
static const bool initialized = [] () {
|
||||
signal (SIGPIPE, SIG_IGN);
|
||||
char *loc = setlocale (LC_ALL, "");
|
||||
if (!loc || string (loc) == "C") setlocale (LC_ALL, "en_US.UTF-8");
|
||||
return true;
|
||||
} ();
|
||||
(void) initialized;
|
||||
}
|
||||
|
||||
CoreUnix::~CoreUnix ()
|
||||
@@ -521,13 +525,42 @@ namespace VeraCrypt
|
||||
return mountedFilesystems.front()->MountPoint;
|
||||
}
|
||||
|
||||
shared_ptr <VolumeInfo> CoreUnix::ReadAuxiliaryVolumeInfo (const DirectoryPath &auxMountPoint)
|
||||
{
|
||||
File control;
|
||||
control.Open (string (auxMountPoint) + FuseService::GetControlPath());
|
||||
Buffer buffer (8192);
|
||||
string data;
|
||||
for (uint64 count; (count = control.Read (buffer)) != 0; )
|
||||
{
|
||||
if (data.size() + count > 1024 * 1024) throw ParameterTooLarge (SRC_POS);
|
||||
data.append (reinterpret_cast <const char *> (buffer.Ptr()), count);
|
||||
}
|
||||
shared_ptr <Stream> stream (new MemoryStream (ConstBufferPtr (reinterpret_cast <const uint8 *> (data.data()), data.size())));
|
||||
shared_ptr <VolumeInfo> volume = Serializable::DeserializeNew <VolumeInfo> (stream);
|
||||
volume->AuxMountPoint = auxMountPoint;
|
||||
return volume;
|
||||
}
|
||||
|
||||
VolumeInfoList CoreUnix::GetMountedVolumes (const VolumePath &volumePath) const
|
||||
{
|
||||
VolumeInfoList volumes;
|
||||
VolumeDiscoveryResult result = GetMountedVolumesWithStatus (volumePath);
|
||||
if (!result.IsComplete()) throw VolumeDiscoveryFailed (SRC_POS, wstring (result.UnresolvedMounts.front()));
|
||||
return result.Volumes;
|
||||
}
|
||||
|
||||
VolumeDiscoveryResult CoreUnix::GetMountedVolumesWithStatus (const VolumePath &volumePath) const
|
||||
{
|
||||
VolumeDiscoveryResult result;
|
||||
VolumeInfoList &volumes = result.Volumes;
|
||||
|
||||
foreach_ref (const MountedFilesystem &mf, GetMountedFilesystems ())
|
||||
{
|
||||
#ifdef TC_MACOSX
|
||||
if (!mf.IsAuxiliaryMountCandidate (GetFuseMountDirPrefix(), getuid(), GetRealUserId()))
|
||||
#else
|
||||
if (string (mf.MountPoint).find (GetFuseMountDirPrefix()) == string::npos)
|
||||
#endif
|
||||
continue;
|
||||
|
||||
shared_ptr <VolumeInfo> mountedVol;
|
||||
@@ -542,16 +575,7 @@ namespace VeraCrypt
|
||||
{
|
||||
try
|
||||
{
|
||||
shared_ptr <File> controlFile (new File);
|
||||
controlFile->Open (string (mf.MountPoint) + FuseService::GetControlPath());
|
||||
|
||||
FileStream controlFileReader (controlFile);
|
||||
string controlFileData = controlFileReader.ReadToEnd();
|
||||
if (controlFileData.empty() || controlFileData.size() > 1024 * 1024)
|
||||
throw ParameterIncorrect (SRC_POS);
|
||||
|
||||
shared_ptr <Stream> controlFileStream (new MemoryStream (ConstBufferPtr ((const uint8 *) controlFileData.data(), controlFileData.size())));
|
||||
mountedVol = Serializable::DeserializeNew <VolumeInfo> (controlFileStream);
|
||||
mountedVol = ReadAuxiliaryVolumeInfo (mf.MountPoint);
|
||||
}
|
||||
catch (const std::exception& e)
|
||||
{
|
||||
@@ -581,7 +605,7 @@ namespace VeraCrypt
|
||||
#endif
|
||||
}
|
||||
|
||||
if (!mountedVol)
|
||||
if (!mountedVol)
|
||||
{
|
||||
#ifdef VC_MACOSX_FUSET
|
||||
if (!volumePath.IsEmpty())
|
||||
@@ -594,7 +618,10 @@ namespace VeraCrypt
|
||||
SystemLog::WriteError (logMessage.str());
|
||||
}
|
||||
#endif
|
||||
continue; // Skip to the next mounted filesystem
|
||||
#ifdef TC_MACOSX
|
||||
result.UnresolvedMounts.push_back (mf.MountPoint);
|
||||
#endif
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!volumePath.IsEmpty() && wstring (mountedVol->Path).compare (volumePath) != 0)
|
||||
@@ -602,12 +629,7 @@ namespace VeraCrypt
|
||||
|
||||
mountedVol->AuxMountPoint = mf.MountPoint;
|
||||
|
||||
#ifdef TC_MACOSX
|
||||
// The control file can retain a disk number after detach. Always resolve
|
||||
// the image first, before consulting the mount table for that device.
|
||||
try { UpdateMountedVolumeInfo (mountedVol); }
|
||||
catch (exception &e) { SystemLog::WriteException (e); }
|
||||
#else
|
||||
#ifndef TC_MACOSX
|
||||
if (mountedVol->MountPoint.IsEmpty() && !mountedVol->VirtualDevice.IsEmpty())
|
||||
{
|
||||
MountedFilesystemList mpl = GetMountedFilesystems (mountedVol->VirtualDevice);
|
||||
@@ -626,9 +648,20 @@ namespace VeraCrypt
|
||||
break;
|
||||
}
|
||||
|
||||
return volumes;
|
||||
#ifdef TC_MACOSX
|
||||
UpdateMountedVolumesInfo (volumes);
|
||||
#endif
|
||||
return result;
|
||||
}
|
||||
|
||||
#ifdef TC_MACOSX
|
||||
void CoreUnix::UpdateMountedVolumesInfo (VolumeInfoList &volumes) const
|
||||
{
|
||||
foreach (shared_ptr <VolumeInfo> volume, volumes)
|
||||
UpdateMountedVolumeInfo (volume);
|
||||
}
|
||||
#endif
|
||||
|
||||
gid_t CoreUnix::GetRealGroupId () const
|
||||
{
|
||||
const char *env = getenv ("SUDO_GID");
|
||||
@@ -1146,7 +1179,6 @@ namespace VeraCrypt
|
||||
mountDirectory.push_back ('\0');
|
||||
throw_sys_if (mkdtemp (&mountDirectory[0]) == NULL);
|
||||
fuseMountPoint = &mountDirectory[0];
|
||||
throw_sys_if (chmod (fuseMountPoint.c_str(), S_IRUSR | S_IXUSR) == -1);
|
||||
#else
|
||||
// Find a free mount point for FUSE service
|
||||
MountedFilesystemList mountedFilesystems = GetMountedFilesystems ();
|
||||
@@ -1194,6 +1226,9 @@ namespace VeraCrypt
|
||||
|
||||
try
|
||||
{
|
||||
#ifdef VC_MACOSX_FUSET
|
||||
throw_sys_if (chmod (fuseMountPoint.c_str(), S_IRUSR | S_IXUSR) == -1);
|
||||
#endif
|
||||
#ifdef TC_MACOSX
|
||||
// FUSE canonicalizes its mount path. Give hdiutil the same path so
|
||||
// its inventory identifies the image even when TMPDIR is a symlink.
|
||||
@@ -1277,34 +1312,46 @@ namespace VeraCrypt
|
||||
}
|
||||
#endif
|
||||
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
try
|
||||
#ifdef VC_MACOSX_FUSET
|
||||
shared_ptr <VolumeInfo> mountedVolume = GetMountedVolume (*options.Path);
|
||||
if (mountedVolume)
|
||||
{
|
||||
VolumeInfoList mountedVolumes = GetMountedVolumes (*options.Path);
|
||||
if (mountedVolumes.size() > 0)
|
||||
if (mountedVolume->SerialInstanceNumber != fuseServiceSerialInstanceNumber)
|
||||
throw ParameterIncorrect (SRC_POS);
|
||||
if (!mountedVirtualDevice.IsEmpty())
|
||||
{
|
||||
shared_ptr <VolumeInfo> mountedVolume (mountedVolumes.front());
|
||||
DismountVolume (mountedVolume);
|
||||
if (mountedVolume->VirtualDevice.IsEmpty())
|
||||
mountedVolume->VirtualDevice = mountedVirtualDevice;
|
||||
|
||||
if (!options.NoFilesystem && mountedVolume->MountPoint.IsEmpty())
|
||||
{
|
||||
for (int mountPointRetries = 20; mountPointRetries > 0; --mountPointRetries)
|
||||
{
|
||||
try
|
||||
{
|
||||
mountedVolume->MountPoint = GetDeviceMountPoint (mountedVirtualDevice);
|
||||
if (!mountedVolume->MountPoint.IsEmpty())
|
||||
break;
|
||||
}
|
||||
catch (...) { }
|
||||
|
||||
Thread::Sleep (500);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (...) { }
|
||||
throw;
|
||||
}
|
||||
|
||||
#ifdef VC_MACOSX_FUSET
|
||||
VolumeInfoList mountedVolumes = GetMountedVolumes (*options.Path);
|
||||
shared_ptr <VolumeInfo> mountedVolume;
|
||||
if (mountedVolumes.size() == 1)
|
||||
{
|
||||
mountedVolume = mountedVolumes.front();
|
||||
if (!mountedVirtualDevice.IsEmpty())
|
||||
else if (!mountedVirtualDevice.IsEmpty())
|
||||
{
|
||||
if (mountedVolume->VirtualDevice.IsEmpty())
|
||||
mountedVolume->VirtualDevice = mountedVirtualDevice;
|
||||
mountedVolume.reset (new VolumeInfo);
|
||||
mountedVolume->Set (*volume);
|
||||
mountedVolume->ProgramVersion = VERSION_NUM;
|
||||
mountedVolume->SlotNumber = options.SlotNumber;
|
||||
mountedVolume->AuxMountPoint = fuseMountPoint;
|
||||
mountedVolume->VirtualDevice = mountedVirtualDevice;
|
||||
|
||||
if (!options.NoFilesystem && mountedVolume->MountPoint.IsEmpty())
|
||||
mountedVolume->SerialInstanceNumber = fuseServiceSerialInstanceNumber;
|
||||
|
||||
if (!options.NoFilesystem)
|
||||
{
|
||||
for (int mountPointRetries = 20; mountPointRetries > 0; --mountPointRetries)
|
||||
{
|
||||
@@ -1320,47 +1367,56 @@ namespace VeraCrypt
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (!mountedVirtualDevice.IsEmpty())
|
||||
{
|
||||
mountedVolume.reset (new VolumeInfo);
|
||||
mountedVolume->Set (*volume);
|
||||
mountedVolume->ProgramVersion = VERSION_NUM;
|
||||
mountedVolume->SlotNumber = options.SlotNumber;
|
||||
mountedVolume->AuxMountPoint = fuseMountPoint;
|
||||
mountedVolume->VirtualDevice = mountedVirtualDevice;
|
||||
|
||||
mountedVolume->SerialInstanceNumber = fuseServiceSerialInstanceNumber;
|
||||
|
||||
if (!options.NoFilesystem)
|
||||
{
|
||||
for (int mountPointRetries = 20; mountPointRetries > 0; --mountPointRetries)
|
||||
{
|
||||
try
|
||||
{
|
||||
mountedVolume->MountPoint = GetDeviceMountPoint (mountedVirtualDevice);
|
||||
if (!mountedVolume->MountPoint.IsEmpty())
|
||||
break;
|
||||
}
|
||||
catch (...) { }
|
||||
|
||||
Thread::Sleep (500);
|
||||
}
|
||||
}
|
||||
}
|
||||
#else
|
||||
VolumeInfoList mountedVolumes = GetMountedVolumes (*options.Path);
|
||||
shared_ptr <VolumeInfo> mountedVolume;
|
||||
if (mountedVolumes.size() == 1)
|
||||
mountedVolume = mountedVolumes.front();
|
||||
shared_ptr <VolumeInfo> mountedVolume = GetMountedVolume (*options.Path);
|
||||
#endif
|
||||
if (!mountedVolume)
|
||||
throw ParameterIncorrect (SRC_POS);
|
||||
if (!mountedVolume)
|
||||
throw ParameterIncorrect (SRC_POS);
|
||||
|
||||
VolumeEventArgs eventArgs (mountedVolume);
|
||||
VolumeMountedEvent.Raise (eventArgs);
|
||||
VolumeEventArgs eventArgs (mountedVolume);
|
||||
VolumeMountedEvent.Raise (eventArgs);
|
||||
|
||||
return mountedVolume;
|
||||
return mountedVolume;
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
#ifdef VC_MACOSX_FUSET
|
||||
// Enumeration may itself have failed. Cleanup belongs to the instance
|
||||
// we just started, not a later volume discovered by path or slot.
|
||||
try { throw; }
|
||||
catch (exception &e) { SystemLog::WriteException (e); }
|
||||
catch (...) { }
|
||||
try
|
||||
{
|
||||
shared_ptr <VolumeInfo> cleanupVolume (new VolumeInfo);
|
||||
cleanupVolume->Set (*volume);
|
||||
cleanupVolume->ProgramVersion = VERSION_NUM;
|
||||
cleanupVolume->SlotNumber = options.SlotNumber;
|
||||
cleanupVolume->SerialInstanceNumber = fuseServiceSerialInstanceNumber;
|
||||
cleanupVolume->AuxMountPoint = fuseMountPoint;
|
||||
DismountVolume (cleanupVolume);
|
||||
}
|
||||
catch (DismountServiceCleanupFailed &) { throw; }
|
||||
catch (exception &e)
|
||||
{
|
||||
SystemLog::WriteException (e);
|
||||
throw MountServiceCleanupFailed (SRC_POS, StringConverter::ToWide (fuseMountPoint) + L"\n" + StringConverter::ToExceptionString (e));
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
throw MountServiceCleanupFailed (SRC_POS, StringConverter::ToWide (fuseMountPoint));
|
||||
}
|
||||
#else
|
||||
try
|
||||
{
|
||||
shared_ptr <VolumeInfo> mountedVolume = GetMountedVolume (*options.Path);
|
||||
if (mountedVolume)
|
||||
DismountVolume (mountedVolume);
|
||||
}
|
||||
catch (...) { }
|
||||
#endif
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
DevicePath CoreUnix::MountAuxVolumeImage (const DirectoryPath &auxMountPoint, const MountOptions &options) const
|
||||
|
||||
@@ -39,6 +39,7 @@ namespace VeraCrypt
|
||||
virtual int GetOSMajorVersion () const { throw NotApplicable (SRC_POS); }
|
||||
virtual int GetOSMinorVersion () const { throw NotApplicable (SRC_POS); }
|
||||
virtual VolumeInfoList GetMountedVolumes (const VolumePath &volumePath = VolumePath()) const;
|
||||
virtual VolumeDiscoveryResult GetMountedVolumesWithStatus (const VolumePath &volumePath = VolumePath()) const;
|
||||
virtual bool IsDevicePresent (const DevicePath &device) const { throw NotApplicable (SRC_POS); }
|
||||
virtual bool IsInPortableMode () const { return false; }
|
||||
virtual bool IsMountPointAvailable (const DirectoryPath &mountPoint) const;
|
||||
@@ -55,6 +56,7 @@ namespace VeraCrypt
|
||||
virtual bool IsDirectoryOnUserPath(const DirectoryPath &directory) const;
|
||||
|
||||
protected:
|
||||
static shared_ptr <VolumeInfo> ReadAuxiliaryVolumeInfo (const DirectoryPath &auxMountPoint);
|
||||
virtual DevicePath AttachFileToLoopDevice (const FilePath &filePath, bool readOnly) const { throw NotApplicable (SRC_POS); }
|
||||
virtual void DetachLoopDevice (const DevicePath &devicePath) const { throw NotApplicable (SRC_POS); }
|
||||
virtual void DismountNativeVolume (shared_ptr <VolumeInfo> mountedVolume) const { throw NotApplicable (SRC_POS); }
|
||||
@@ -75,6 +77,9 @@ namespace VeraCrypt
|
||||
virtual DevicePath MountAuxVolumeImage (const DirectoryPath &auxMountPoint, const MountOptions &options) const;
|
||||
virtual void MountVolumeNative (shared_ptr <Volume> volume, MountOptions &options, const DirectoryPath &auxMountPoint) const { throw NotApplicable (SRC_POS); }
|
||||
virtual void UpdateMountedVolumeInfo (shared_ptr <VolumeInfo> mountedVolume) const { (void) mountedVolume; }
|
||||
#ifdef TC_MACOSX
|
||||
virtual void UpdateMountedVolumesInfo (VolumeInfoList &volumes) const;
|
||||
#endif
|
||||
#ifdef TC_LINUX
|
||||
string DetectFilesystemType (const DevicePath &devicePath) const;
|
||||
bool IsFilesystemTypeRegistered (const string &filesystemType) const;
|
||||
|
||||
@@ -153,7 +153,12 @@ namespace VeraCrypt
|
||||
MountedFilesystemList CoreFreeBSD::GetMountedFilesystems (const DevicePath &devicePath, const DirectoryPath &mountPoint) const
|
||||
{
|
||||
|
||||
#ifdef TC_MACOSX
|
||||
// A detached discovery worker can finish during static teardown.
|
||||
static Mutex &mutex = *new Mutex;
|
||||
#else
|
||||
static Mutex mutex;
|
||||
#endif
|
||||
ScopeLock sl (mutex);
|
||||
|
||||
struct statfs *sysMountList;
|
||||
@@ -175,6 +180,11 @@ namespace VeraCrypt
|
||||
mf->MountPoint = DirectoryPath (sysMountList[i].f_mntonname);
|
||||
|
||||
mf->Type = sysMountList[i].f_fstypename;
|
||||
#ifdef TC_MACOSX
|
||||
mf->Owner = sysMountList[i].f_owner;
|
||||
mf->MountId[0] = sysMountList[i].f_fsid.val[0];
|
||||
mf->MountId[1] = sysMountList[i].f_fsid.val[1];
|
||||
#endif
|
||||
|
||||
if ((devicePath.IsEmpty() || devicePath == mf->Device) && (mountPoint.IsEmpty() || mountPoint == mf->MountPoint))
|
||||
mountedFilesystems.push_back (mf);
|
||||
|
||||
@@ -170,66 +170,84 @@ namespace VeraCrypt
|
||||
return ExtractDeviceAndMountPointFromEntities ((CFArrayRef) entities, device, mountPoint);
|
||||
}
|
||||
|
||||
static bool FindDiskImageInfoByImagePath (const string &imagePath, DevicePath &device, DirectoryPath &mountPoint)
|
||||
static string GetDiskImageInventory ()
|
||||
{
|
||||
list <string> args;
|
||||
args.push_back ("info");
|
||||
args.push_back ("-plist");
|
||||
return Process::ExecuteBounded ("/usr/bin/hdiutil", args, 2000);
|
||||
}
|
||||
|
||||
string xml = Process::Execute ("/usr/bin/hdiutil", args);
|
||||
static bool FindDiskImageInfoByImagePath (const string &xml, const string &imagePath, DevicePath &device, DirectoryPath &mountPoint)
|
||||
{
|
||||
string canonicalImagePath = CanonicalizeDiskImagePath (imagePath);
|
||||
// TMPDIR aliases change the parent path, not VeraCrypt's auxiliary
|
||||
// directory name or the image filename appended to it.
|
||||
size_t imageSeparator = canonicalImagePath.find_last_of ('/');
|
||||
if (imageSeparator == string::npos || imageSeparator == 0)
|
||||
throw ParameterIncorrect (SRC_POS);
|
||||
size_t auxiliarySeparator = canonicalImagePath.find_last_of ('/', imageSeparator - 1);
|
||||
if (imageSeparator == string::npos || auxiliarySeparator == string::npos)
|
||||
if (auxiliarySeparator == string::npos)
|
||||
throw ParameterIncorrect (SRC_POS);
|
||||
const string imageSuffix = canonicalImagePath.substr (auxiliarySeparator);
|
||||
|
||||
CFHolder plist (ParsePropertyList (xml));
|
||||
if (!plist.Get() || CFGetTypeID (plist.Get()) != CFDictionaryGetTypeID())
|
||||
throw ParameterIncorrect (SRC_POS);
|
||||
|
||||
CFTypeRef images = CFDictionaryGetValue ((CFDictionaryRef) plist.Get(), CFSTR ("images")); // borrowed
|
||||
CFTypeRef images = CFDictionaryGetValue ((CFDictionaryRef) plist.Get(), CFSTR ("images"));
|
||||
if (!images || CFGetTypeID (images) != CFArrayGetTypeID())
|
||||
throw ParameterIncorrect (SRC_POS);
|
||||
|
||||
CFArrayRef imageArray = (CFArrayRef) images;
|
||||
CFIndex count = CFArrayGetCount (imageArray);
|
||||
for (CFIndex i = 0; i < count; ++i)
|
||||
bool uncertain = false;
|
||||
// Positive exact matches take precedence over unreadable unrelated images.
|
||||
// Only the second pass touches paths used by older TMPDIR aliases.
|
||||
for (int pass = 0; pass < 2; ++pass)
|
||||
{
|
||||
CFTypeRef image = CFArrayGetValueAtIndex (imageArray, i); // borrowed
|
||||
if (!image || CFGetTypeID (image) != CFDictionaryGetTypeID())
|
||||
throw ParameterIncorrect (SRC_POS);
|
||||
|
||||
CFDictionaryRef imageDict = (CFDictionaryRef) image;
|
||||
|
||||
string currentImagePath = CFDictionaryGetStdString (imageDict, "image-path");
|
||||
if (currentImagePath.empty())
|
||||
throw ParameterIncorrect (SRC_POS);
|
||||
if (currentImagePath != canonicalImagePath)
|
||||
for (CFIndex i = 0; i < CFArrayGetCount (imageArray); ++i)
|
||||
{
|
||||
// Older clients attached through TMPDIR aliases. Resolve those too,
|
||||
// but do not access unrelated disk images (which may be offline).
|
||||
if (currentImagePath[0] != '/' || currentImagePath.size() < imageSuffix.size()
|
||||
|| currentImagePath.compare (currentImagePath.size() - imageSuffix.size(), imageSuffix.size(), imageSuffix) != 0)
|
||||
CFTypeRef image = CFArrayGetValueAtIndex (imageArray, i);
|
||||
if (!image || CFGetTypeID (image) != CFDictionaryGetTypeID())
|
||||
{
|
||||
uncertain = true;
|
||||
continue;
|
||||
// Failure to resolve a candidate is not proof that our image is gone.
|
||||
if (CanonicalizeDiskImagePath (currentImagePath) != canonicalImagePath)
|
||||
}
|
||||
CFDictionaryRef imageDict = (CFDictionaryRef) image;
|
||||
string currentImagePath = CFDictionaryGetStdString (imageDict, "image-path");
|
||||
if (currentImagePath.empty())
|
||||
{
|
||||
uncertain = true;
|
||||
continue;
|
||||
}
|
||||
if (pass == 0)
|
||||
{
|
||||
if (currentImagePath != canonicalImagePath) continue;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (currentImagePath == canonicalImagePath || currentImagePath[0] != '/'
|
||||
|| currentImagePath.size() < imageSuffix.size()
|
||||
|| currentImagePath.compare (currentImagePath.size() - imageSuffix.size(), imageSuffix.size(), imageSuffix) != 0)
|
||||
continue;
|
||||
try
|
||||
{
|
||||
if (CanonicalizeDiskImagePath (currentImagePath) != canonicalImagePath) continue;
|
||||
}
|
||||
catch (exception &)
|
||||
{
|
||||
uncertain = true;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
CFTypeRef entities = CFDictionaryGetValue (imageDict, CFSTR ("system-entities"));
|
||||
if (!entities || CFGetTypeID (entities) != CFArrayGetTypeID()
|
||||
|| !ExtractDeviceAndMountPointFromEntities ((CFArrayRef) entities, device, mountPoint))
|
||||
throw ParameterIncorrect (SRC_POS);
|
||||
return true;
|
||||
}
|
||||
|
||||
// A missing image and an unreadable inventory are different states.
|
||||
// Callers must never fall back to a cached disk number on an error.
|
||||
CFTypeRef entities = CFDictionaryGetValue (imageDict, CFSTR ("system-entities")); // borrowed
|
||||
if (!entities || CFGetTypeID (entities) != CFArrayGetTypeID())
|
||||
throw ParameterIncorrect (SRC_POS);
|
||||
|
||||
if (!ExtractDeviceAndMountPointFromEntities ((CFArrayRef) entities, device, mountPoint))
|
||||
throw ParameterIncorrect (SRC_POS);
|
||||
return true;
|
||||
}
|
||||
|
||||
// A partial inventory cannot establish absence. In particular, never
|
||||
// substitute a cached BSD disk number when ownership is unknown.
|
||||
if (uncertain) throw ParameterIncorrect (SRC_POS);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -268,6 +286,21 @@ namespace VeraCrypt
|
||||
{
|
||||
}
|
||||
|
||||
shared_ptr <VolumeInfo> CoreMacOSX::ValidateMountedVolume (shared_ptr <VolumeInfo> volume) const
|
||||
{
|
||||
if (!volume || volume->AuxMountPoint.IsEmpty()) throw ParameterIncorrect (SRC_POS);
|
||||
MountedFilesystemList before = GetMountedFilesystems (DevicePath(), volume->AuxMountPoint);
|
||||
if (before.size() != 1) throw MountServiceUnavailable (SRC_POS, wstring (volume->AuxMountPoint));
|
||||
shared_ptr <VolumeInfo> current = ReadAuxiliaryVolumeInfo (volume->AuxMountPoint);
|
||||
MountedFilesystemList after = GetMountedFilesystems (DevicePath(), volume->AuxMountPoint);
|
||||
if (after.size() != 1 || before.front()->MountId[0] != after.front()->MountId[0]
|
||||
|| before.front()->MountId[1] != after.front()->MountId[1]
|
||||
|| current->SerialInstanceNumber != volume->SerialInstanceNumber
|
||||
|| current->SlotNumber != volume->SlotNumber || current->Path != volume->Path)
|
||||
throw MountServiceUnavailable (SRC_POS, wstring (volume->AuxMountPoint));
|
||||
return current;
|
||||
}
|
||||
|
||||
shared_ptr <VolumeInfo> CoreMacOSX::DismountVolume (shared_ptr <VolumeInfo> mountedVolume, bool ignoreOpenFiles, bool syncVolumeInfo)
|
||||
{
|
||||
if (!mountedVolume || mountedVolume->AuxMountPoint.IsEmpty())
|
||||
@@ -277,19 +310,20 @@ namespace VeraCrypt
|
||||
// the disk image. Retain its identity independently of SMB metadata.
|
||||
const FuseService::DismountRequest dismountRequest = FuseService::PrepareDismount (mountedVolume->AuxMountPoint,
|
||||
mountedVolume->SerialInstanceNumber, mountedVolume->SlotNumber, ignoreOpenFiles);
|
||||
#else
|
||||
mountedVolume = ValidateMountedVolume (mountedVolume);
|
||||
#endif
|
||||
|
||||
// Resolve ownership immediately before detach, including retries after a
|
||||
// busy auxiliary unmount or an external eject. BSD disk numbers are reused.
|
||||
#ifdef VC_MACOSX_FUSET
|
||||
if (!FuseService::IsDismountMountPresent (dismountRequest))
|
||||
if (FuseService::IsDismountMountPresent (dismountRequest))
|
||||
{
|
||||
if (!dismountRequest.LegacyService)
|
||||
FuseService::WaitForDismount (FuseService::RequestDismount (dismountRequest), mountedVolume->AuxMountPoint, mountedVolume->SlotNumber);
|
||||
return mountedVolume;
|
||||
}
|
||||
#endif
|
||||
UpdateMountedVolumeInfo (mountedVolume);
|
||||
#ifndef VC_MACOSX_FUSET
|
||||
ValidateMountedVolume (mountedVolume);
|
||||
#endif
|
||||
|
||||
if (!mountedVolume->VirtualDevice.IsEmpty() && mountedVolume->VirtualDevice.IsBlockDevice()
|
||||
#ifdef VC_MACOSX_FUSET
|
||||
@@ -329,18 +363,31 @@ namespace VeraCrypt
|
||||
if (syncVolumeInfo || mountedVolume->Protection == VolumeProtection::HiddenVolumeReadOnly)
|
||||
{
|
||||
sync();
|
||||
VolumeInfoList ml = GetMountedVolumes (mountedVolume->Path);
|
||||
|
||||
if (ml.size() > 0 && ml.front()->SerialInstanceNumber == mountedVolume->SerialInstanceNumber)
|
||||
mountedVolume = ml.front();
|
||||
// Refresh only the captured service. Other users' auxiliary mounts
|
||||
// must not interrupt teardown after the disk image has been detached.
|
||||
mountedVolume = ValidateMountedVolume (mountedVolume);
|
||||
}
|
||||
|
||||
#ifdef VC_MACOSX_FUSET
|
||||
}
|
||||
// The service unmounts SMB while its FUSE loop can still answer requests.
|
||||
if (!dismountRequest.LegacyService)
|
||||
{
|
||||
pid_t fuseServiceProcessId = FuseService::RequestDismount (dismountRequest);
|
||||
FuseService::WaitForDismount (fuseServiceProcessId, mountedVolume->AuxMountPoint, mountedVolume->SlotNumber);
|
||||
try
|
||||
{
|
||||
if (FuseService::IsDismountMountPresent (dismountRequest))
|
||||
FuseService::RequestDismount (dismountRequest);
|
||||
FuseService::WaitForDismount (dismountRequest.ProcessId, mountedVolume->AuxMountPoint, mountedVolume->SlotNumber, 10000, dismountRequest.ProcessStartTime);
|
||||
}
|
||||
catch (DismountServiceCleanupFailed &) { throw; }
|
||||
catch (exception &e)
|
||||
{
|
||||
// Without SMB, the volume can no longer be discovered or retried.
|
||||
// Report the unconfirmed service exit with the original details.
|
||||
if (FuseService::IsDismountMountPresent (dismountRequest))
|
||||
throw;
|
||||
throw DismountServiceCleanupFailed (SRC_POS, StringConverter::ToExceptionString (e));
|
||||
}
|
||||
}
|
||||
else
|
||||
FuseService::DismountLegacy (dismountRequest);
|
||||
@@ -365,41 +412,70 @@ namespace VeraCrypt
|
||||
}
|
||||
#endif
|
||||
|
||||
try
|
||||
{
|
||||
mountedVolume->AuxMountPoint.Delete();
|
||||
}
|
||||
catch (...) { }
|
||||
// Current services remove their original directory. Older development
|
||||
// services may leave it behind; rmdir only removes an empty directory
|
||||
// and cannot follow a replacement symlink or remove a mounted filesystem.
|
||||
rmdir (string (mountedVolume->AuxMountPoint).c_str());
|
||||
|
||||
return mountedVolume;
|
||||
}
|
||||
|
||||
void CoreMacOSX::UpdateMountedVolumeInfo (shared_ptr <VolumeInfo> mountedVolume) const
|
||||
static void ClearDiskImageInfo (shared_ptr <VolumeInfo> volume)
|
||||
{
|
||||
if (!mountedVolume)
|
||||
return;
|
||||
volume->VirtualDevice = DevicePath();
|
||||
volume->MountPoint = DirectoryPath();
|
||||
volume->Discovery = VolumeInfo::DiscoveryUnknown;
|
||||
}
|
||||
|
||||
// Clear stale metadata even if discovery fails. Destructive callers get
|
||||
// the exception; enumeration can still show the auxiliary mount for retry.
|
||||
mountedVolume->VirtualDevice = DevicePath();
|
||||
mountedVolume->MountPoint = DirectoryPath();
|
||||
if (mountedVolume->AuxMountPoint.IsEmpty())
|
||||
return;
|
||||
DevicePath recoveredVirtualDevice;
|
||||
DirectoryPath recoveredMountPoint;
|
||||
if (!FindDiskImageInfoByImagePath (string (mountedVolume->AuxMountPoint) + FuseService::GetVolumeImagePath(), recoveredVirtualDevice, recoveredMountPoint))
|
||||
return;
|
||||
mountedVolume->VirtualDevice = recoveredVirtualDevice;
|
||||
mountedVolume->MountPoint = recoveredMountPoint;
|
||||
void CoreMacOSX::UpdateMountedVolumesInfo (VolumeInfoList &volumes) const
|
||||
{
|
||||
foreach (shared_ptr <VolumeInfo> volume, volumes)
|
||||
ClearDiskImageInfo (volume);
|
||||
if (volumes.empty()) return;
|
||||
try
|
||||
{
|
||||
// One inventory per enumeration, regardless of the volume count.
|
||||
const string inventory = GetDiskImageInventory();
|
||||
foreach (shared_ptr <VolumeInfo> volume, volumes)
|
||||
{
|
||||
try { UpdateMountedVolumeInfo (volume, inventory); }
|
||||
catch (exception &e) { SystemLog::WriteException (e); }
|
||||
}
|
||||
}
|
||||
catch (exception &e) { SystemLog::WriteException (e); }
|
||||
}
|
||||
|
||||
if (mountedVolume->MountPoint.IsEmpty() && !mountedVolume->VirtualDevice.IsEmpty())
|
||||
void CoreMacOSX::UpdateMountedVolumeInfo (shared_ptr <VolumeInfo> volume) const
|
||||
{
|
||||
if (!volume) return;
|
||||
ClearDiskImageInfo (volume);
|
||||
try { UpdateMountedVolumeInfo (volume, GetDiskImageInventory()); }
|
||||
catch (exception &e)
|
||||
{
|
||||
throw VolumeDiscoveryFailed (SRC_POS, StringConverter::ToExceptionString (e));
|
||||
}
|
||||
}
|
||||
|
||||
void CoreMacOSX::UpdateMountedVolumeInfo (shared_ptr <VolumeInfo> volume, const string &inventory) const
|
||||
{
|
||||
ClearDiskImageInfo (volume);
|
||||
if (volume->AuxMountPoint.IsEmpty()) throw ParameterIncorrect (SRC_POS);
|
||||
DevicePath device;
|
||||
DirectoryPath mountPoint;
|
||||
if (!FindDiskImageInfoByImagePath (inventory, string (volume->AuxMountPoint) + FuseService::GetVolumeImagePath(), device, mountPoint))
|
||||
{
|
||||
volume->Discovery = VolumeInfo::ImageAbsent;
|
||||
return;
|
||||
}
|
||||
volume->VirtualDevice = device;
|
||||
volume->MountPoint = mountPoint;
|
||||
volume->Discovery = VolumeInfo::ImageAttached;
|
||||
if (volume->MountPoint.IsEmpty())
|
||||
{
|
||||
try
|
||||
{
|
||||
MountedFilesystemList mountedFilesystems = GetMountedFilesystems (mountedVolume->VirtualDevice);
|
||||
|
||||
if (mountedFilesystems.size() > 0)
|
||||
mountedVolume->MountPoint = mountedFilesystems.front()->MountPoint;
|
||||
MountedFilesystemList filesystems = GetMountedFilesystems (device);
|
||||
if (!filesystems.empty()) volume->MountPoint = filesystems.front()->MountPoint;
|
||||
}
|
||||
catch (...) { }
|
||||
}
|
||||
@@ -438,7 +514,9 @@ namespace VeraCrypt
|
||||
|
||||
void CoreMacOSX::CheckFilesystem (shared_ptr <VolumeInfo> mountedVolume, bool repair) const
|
||||
{
|
||||
mountedVolume = ValidateMountedVolume (mountedVolume);
|
||||
UpdateMountedVolumeInfo (mountedVolume);
|
||||
ValidateMountedVolume (mountedVolume);
|
||||
// Honor the check-vs-repair distinction by running diskutil on the VeraCrypt
|
||||
// virtual device (diskutil unmounts the inner filesystem itself as needed).
|
||||
// The Core layer has no GUI, so results are shown in a Terminal window via a
|
||||
|
||||
@@ -31,10 +31,13 @@ namespace VeraCrypt
|
||||
protected:
|
||||
virtual DevicePath MountAuxVolumeImage (const DirectoryPath &auxMountPoint, const MountOptions &options) const;
|
||||
virtual void UpdateMountedVolumeInfo (shared_ptr <VolumeInfo> mountedVolume) const;
|
||||
virtual void UpdateMountedVolumesInfo (VolumeInfoList &volumes) const;
|
||||
|
||||
private:
|
||||
CoreMacOSX (const CoreMacOSX &);
|
||||
CoreMacOSX &operator= (const CoreMacOSX &);
|
||||
void UpdateMountedVolumeInfo (shared_ptr <VolumeInfo> volume, const string &inventory) const;
|
||||
shared_ptr <VolumeInfo> ValidateMountedVolume (shared_ptr <VolumeInfo> volume) const;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -20,6 +20,18 @@ namespace VeraCrypt
|
||||
struct MountedFilesystem
|
||||
{
|
||||
public:
|
||||
#ifdef TC_MACOSX
|
||||
MountedFilesystem () : Owner (static_cast <uid_t> (-1)) { MountId[0] = MountId[1] = 0; }
|
||||
bool IsAuxiliaryMountCandidate (const string &prefix, uid_t userId, uid_t realUserId) const
|
||||
{
|
||||
const string name = MountPoint.ToBaseName();
|
||||
return name.compare (0, prefix.size(), prefix) == 0
|
||||
&& (Owner == userId || Owner == 0 || (userId == 0 && Owner == realUserId))
|
||||
&& (Type == "smbfs" || Type == "nfs" || Type == "macfuse" || Type == "osxfuse" || Type == "fusefs");
|
||||
}
|
||||
uid_t Owner;
|
||||
int32 MountId[2];
|
||||
#endif
|
||||
DevicePath Device;
|
||||
DirectoryPath MountPoint;
|
||||
string Type;
|
||||
|
||||
+100
-29
@@ -372,19 +372,22 @@ namespace VeraCrypt
|
||||
for (;;)
|
||||
{
|
||||
bool present = MountPresent();
|
||||
if (StartupCancelled())
|
||||
if (StartupCancelled() && (!present || FuseServiceClock::now() >= NextRollbackAttempt))
|
||||
{
|
||||
// No disk image has been attached yet. Roll back independently
|
||||
// of SMB metadata and the public shutdown socket, while FUSE
|
||||
// can still answer the auxiliary filesystem's final requests.
|
||||
if (present && unmount (MountPoint, MNT_FORCE) != 0)
|
||||
int error = present && unmount (MountPoint, MNT_FORCE) != 0 ? errno : 0;
|
||||
if ((error == EINVAL || error == ENOENT) && !MountPresent())
|
||||
error = 0;
|
||||
if (error == 0)
|
||||
{
|
||||
int error = errno;
|
||||
if ((error != EINVAL && error != ENOENT) || MountPresent())
|
||||
throw SystemException (SRC_POS, error);
|
||||
FinishDismount();
|
||||
return;
|
||||
}
|
||||
FinishDismount();
|
||||
return;
|
||||
// Retry without starving the public endpoint. Probes still validate
|
||||
// this instance; dismount requests can retry and report the error.
|
||||
NextRollbackAttempt = FuseServiceClock::now() + chrono::seconds (1);
|
||||
}
|
||||
// All clients (including released clients and Finder) can remove
|
||||
// SMB without notifying us. Initial absence is not a dismount.
|
||||
@@ -453,10 +456,10 @@ namespace VeraCrypt
|
||||
// finishes. Never act on a replacement at the same path.
|
||||
for (int attempt = 0; !probe && present; ++attempt)
|
||||
{
|
||||
error = unmount (MountPoint, (request[5] & VC_FUSE_SHUTDOWN_FORCE) ? MNT_FORCE : 0) == 0 ? 0 : errno;
|
||||
error = unmount (MountPoint, (StartupAborted || (request[5] & VC_FUSE_SHUTDOWN_FORCE)) ? MNT_FORCE : 0) == 0 ? 0 : errno;
|
||||
if ((error == EINVAL || error == ENOENT) && !MountPresent())
|
||||
error = 0;
|
||||
if (error != EBUSY || attempt == 10)
|
||||
if (error != EBUSY || StartupAborted || attempt == 10)
|
||||
break;
|
||||
Thread::Sleep (200);
|
||||
present = MountPresent();
|
||||
@@ -501,16 +504,71 @@ namespace VeraCrypt
|
||||
bool MountSeen;
|
||||
bool StartupReported;
|
||||
bool StartupAborted;
|
||||
FuseServiceClock::time_point NextRollbackAttempt;
|
||||
fsid_t MountId;
|
||||
unique_ptr <Pipe> StopPipe;
|
||||
Thread ShutdownThread;
|
||||
};
|
||||
|
||||
// Hold the original parent across mounting and teardown, then check the
|
||||
// directory's identity before removing it. Never follow a replacement symlink.
|
||||
class FuseServiceAuxDirectory
|
||||
{
|
||||
public:
|
||||
explicit FuseServiceAuxDirectory (const string &path) : ParentFd (-1)
|
||||
{
|
||||
char *canonicalPath = realpath (path.c_str(), NULL);
|
||||
throw_sys_if (canonicalPath == NULL);
|
||||
finally_do_arg (char *, canonicalPath, { free (finally_arg); });
|
||||
Path = canonicalPath;
|
||||
size_t separator = path.find_last_of ('/');
|
||||
if (separator == string::npos || separator + 1 == path.size())
|
||||
throw ParameterIncorrect (SRC_POS);
|
||||
Name = path.substr (separator + 1);
|
||||
ParentFd = open ((separator == 0 ? "/" : path.substr (0, separator)).c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
|
||||
throw_sys_if (ParentFd == -1);
|
||||
if (fstatat (ParentFd, Name.c_str(), &Original, AT_SYMLINK_NOFOLLOW) != 0 || !S_ISDIR (Original.st_mode))
|
||||
{
|
||||
close (ParentFd);
|
||||
ParentFd = -1;
|
||||
throw ParameterIncorrect (SRC_POS);
|
||||
}
|
||||
}
|
||||
|
||||
~FuseServiceAuxDirectory ()
|
||||
{
|
||||
try
|
||||
{
|
||||
fsid_t mountId;
|
||||
// Do not enter an auxiliary filesystem that may no longer be
|
||||
// served. Its absence is checked without querying the mount itself.
|
||||
if (!fuse_service_find_mount (Path.c_str(), mountId))
|
||||
{
|
||||
struct stat current;
|
||||
if (fstatat (ParentFd, Name.c_str(), ¤t, AT_SYMLINK_NOFOLLOW) == 0
|
||||
&& S_ISDIR (current.st_mode) && current.st_dev == Original.st_dev && current.st_ino == Original.st_ino)
|
||||
unlinkat (ParentFd, Name.c_str(), AT_REMOVEDIR);
|
||||
}
|
||||
}
|
||||
catch (...) { }
|
||||
close (ParentFd);
|
||||
}
|
||||
|
||||
private:
|
||||
int ParentFd;
|
||||
string Name;
|
||||
string Path;
|
||||
struct stat Original;
|
||||
};
|
||||
|
||||
static int fuse_service_main (int argc, char *argv[], const struct fuse_operations *operations, int startupFd)
|
||||
{
|
||||
// On rollback, EOF must only reach the caller after fuse_destroy has
|
||||
// closed the volume. The worker closes this early only after commit.
|
||||
finally_do_arg (int *, &startupFd, { if (*finally_arg != -1) close (*finally_arg); });
|
||||
if (argc < 2)
|
||||
throw ParameterIncorrect (SRC_POS);
|
||||
FuseServiceAuxDirectory auxiliaryDirectory (argv[1]);
|
||||
// FUSE-T execs its backend during setup. This child no longer needs any
|
||||
// inherited descriptors across exec, including helper pipes and /dev/null.
|
||||
const int descriptorLimit = getdtablesize();
|
||||
@@ -1281,7 +1339,9 @@ namespace VeraCrypt
|
||||
#if defined(TC_MACOSX) && defined(VC_MACOSX_FUSET)
|
||||
// Make sure the watcher has observed this mount before a caller can
|
||||
// immediately dismount it with a released (non-notifying) client.
|
||||
PrepareDismount (fuseMountPoint, serialInstanceNumber, slotNumber, false);
|
||||
DismountRequest prepared = PrepareDismount (fuseMountPoint, serialInstanceNumber, slotNumber, false);
|
||||
if (prepared.LegacyService || prepared.ProcessId != startupProcessId)
|
||||
throw ParameterIncorrect (SRC_POS);
|
||||
uint8 commit = 1;
|
||||
if (!fuse_service_socket_transfer (startup[0], &commit, sizeof (commit), true))
|
||||
throw SystemException (SRC_POS, EPIPE);
|
||||
@@ -1415,7 +1475,7 @@ namespace VeraCrypt
|
||||
pid_t peerPid;
|
||||
socklen_t peerPidSize = sizeof (peerPid);
|
||||
throw_sys_if (getsockopt (fd, SOL_LOCAL, LOCAL_PEERPID, &peerPid, &peerPidSize) == -1);
|
||||
if (peerPid != request.ProcessId)
|
||||
if (peerPid != request.ProcessId || !Process::IsProcessRunning (peerPid, request.ProcessStartTime))
|
||||
throw ParameterIncorrect (SRC_POS);
|
||||
return fd;
|
||||
}
|
||||
@@ -1484,6 +1544,7 @@ namespace VeraCrypt
|
||||
if (!fuse_service_parse_shutdown_identity (identity, request.ProcessId, serviceSerialInstanceNumber, serviceSlotNumber)
|
||||
|| serviceSerialInstanceNumber != serialInstanceNumber || serviceSlotNumber != slotNumber)
|
||||
throw ParameterIncorrect (SRC_POS);
|
||||
request.ProcessStartTime = Process::GetProcessStartTime (request.ProcessId);
|
||||
|
||||
try { request.SocketDirectory = fuse_service_read_metadata (request.AuxMountPoint + GetShutdownSocketPath(), 256); }
|
||||
catch (SystemException &e)
|
||||
@@ -1503,11 +1564,22 @@ namespace VeraCrypt
|
||||
if (!fuse_service_request_mount_present (request))
|
||||
throw SystemException (SRC_POS, ESTALE);
|
||||
|
||||
int fd = fuse_service_connect_shutdown (request);
|
||||
finally_do_arg (int, fd, { close (finally_arg); });
|
||||
int32 error = fuse_service_shutdown_command (fd, request, VC_FUSE_SHUTDOWN_PROBE, 10000);
|
||||
if (error != 0)
|
||||
throw SystemException (SRC_POS, error);
|
||||
try
|
||||
{
|
||||
int fd = fuse_service_connect_shutdown (request);
|
||||
finally_do_arg (int, fd, { close (finally_arg); });
|
||||
int32 error = fuse_service_shutdown_command (fd, request, VC_FUSE_SHUTDOWN_PROBE, 10000);
|
||||
if (error != 0)
|
||||
throw SystemException (SRC_POS, error);
|
||||
}
|
||||
catch (SystemException &e)
|
||||
{
|
||||
throw MountServiceUnavailable (SRC_POS, StringConverter::ToExceptionString (e));
|
||||
}
|
||||
catch (TimeOut &e)
|
||||
{
|
||||
throw MountServiceUnavailable (SRC_POS, StringConverter::ToExceptionString (e));
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
@@ -1529,9 +1601,15 @@ namespace VeraCrypt
|
||||
{
|
||||
// External unmount may have completed between preflight and request.
|
||||
// It is only success when the captured mount instance is already gone.
|
||||
if ((e.GetErrorCode() != ENOENT && e.GetErrorCode() != ECONNREFUSED && e.GetErrorCode() != EPIPE)
|
||||
|| fuse_service_request_mount_present (request))
|
||||
if (e.GetErrorCode() != ENOENT && e.GetErrorCode() != ECONNREFUSED && e.GetErrorCode() != EPIPE)
|
||||
throw;
|
||||
if (fuse_service_request_mount_present (request))
|
||||
throw MountServiceUnavailable (SRC_POS, StringConverter::ToExceptionString (e));
|
||||
}
|
||||
catch (TimeOut &e)
|
||||
{
|
||||
if (fuse_service_request_mount_present (request))
|
||||
throw MountServiceUnavailable (SRC_POS, StringConverter::ToExceptionString (e));
|
||||
}
|
||||
return request.ProcessId;
|
||||
}
|
||||
@@ -1563,18 +1641,11 @@ namespace VeraCrypt
|
||||
}
|
||||
}
|
||||
|
||||
void FuseService::WaitForDismount (pid_t processId, const DirectoryPath &fuseMountPoint, VolumeSlotNumber slotNumber, int timeOut)
|
||||
void FuseService::WaitForDismount (pid_t processId, const DirectoryPath &fuseMountPoint, VolumeSlotNumber slotNumber, int timeOut, uint64 processStartTime)
|
||||
{
|
||||
for (int timeTaken = 0; ; timeTaken += 100)
|
||||
{
|
||||
if (kill (processId, 0) == -1)
|
||||
{
|
||||
if (errno == ESRCH)
|
||||
return;
|
||||
|
||||
if (errno != EPERM)
|
||||
throw SystemException (SRC_POS);
|
||||
}
|
||||
if (!Process::IsProcessRunning (processId, processStartTime)) return;
|
||||
|
||||
if (timeTaken >= timeOut)
|
||||
{
|
||||
@@ -1582,7 +1653,7 @@ namespace VeraCrypt
|
||||
logMessage << "VeraCrypt FUSE service did not terminate after shutdown request: pid=" << processId
|
||||
<< ", slot=" << slotNumber << ", auxiliary mount=" << string (fuseMountPoint);
|
||||
SystemLog::WriteError (logMessage.str());
|
||||
throw TimeOut (SRC_POS);
|
||||
throw DismountServiceCleanupFailed (SRC_POS, StringConverter::ToWide (logMessage.str()));
|
||||
}
|
||||
|
||||
Thread::Sleep (100);
|
||||
@@ -1604,7 +1675,7 @@ namespace VeraCrypt
|
||||
{
|
||||
shared_ptr <VolumeInfo> volume = Core->GetMountedVolume (SlotNumber);
|
||||
|
||||
if (volume)
|
||||
if (volume && volume->SerialInstanceNumber == GetSerialInstanceNumber())
|
||||
Core->DismountVolume (volume, true);
|
||||
}
|
||||
catch (...) { }
|
||||
|
||||
@@ -79,6 +79,7 @@ namespace VeraCrypt
|
||||
struct DismountRequest
|
||||
{
|
||||
pid_t ProcessId;
|
||||
uint64 ProcessStartTime;
|
||||
uint64 SerialInstanceNumber;
|
||||
VolumeSlotNumber SlotNumber;
|
||||
bool IgnoreOpenFiles;
|
||||
@@ -92,7 +93,7 @@ namespace VeraCrypt
|
||||
static pid_t RequestDismount (const DismountRequest &request);
|
||||
static bool IsDismountMountPresent (const DismountRequest &request);
|
||||
static void DismountLegacy (const DismountRequest &request);
|
||||
static void WaitForDismount (pid_t processId, const DirectoryPath &fuseMountPoint, VolumeSlotNumber slotNumber, int timeOut = 10000);
|
||||
static void WaitForDismount (pid_t processId, const DirectoryPath &fuseMountPoint, VolumeSlotNumber slotNumber, int timeOut = 10000, uint64 processStartTime = 0);
|
||||
#endif
|
||||
static void WriteVolumeSectors (const ConstBufferPtr &buffer, uint64 byteOffset);
|
||||
|
||||
|
||||
@@ -834,9 +834,10 @@ namespace VeraCrypt
|
||||
return keyfileList;
|
||||
}
|
||||
|
||||
VolumeInfoList CommandLineInterface::GetMountedVolumes (const wxString &mountedVolumeSpec) const
|
||||
VolumeInfoList CommandLineInterface::GetMountedVolumes (const wxString &mountedVolumeSpec)
|
||||
{
|
||||
VolumeInfoList volumes = Core->GetMountedVolumes ();
|
||||
VolumeDiscoveryResult discovery = Core->GetMountedVolumesWithStatus();
|
||||
VolumeInfoList &volumes = discovery.Volumes;
|
||||
VolumeInfoList filteredVolumes;
|
||||
|
||||
wxFileName pathFilter;
|
||||
@@ -846,7 +847,10 @@ namespace VeraCrypt
|
||||
pathFilter.Normalize (wxPATH_NORM_ABSOLUTE | wxPATH_NORM_DOTS);
|
||||
}
|
||||
else
|
||||
{
|
||||
ArgUnresolvedMounts = discovery.UnresolvedMounts;
|
||||
return volumes;
|
||||
}
|
||||
|
||||
foreach (shared_ptr <VolumeInfo> volume, volumes)
|
||||
{
|
||||
@@ -866,7 +870,10 @@ namespace VeraCrypt
|
||||
}
|
||||
|
||||
if (!mountedVolumeSpec.IsEmpty() && filteredVolumes.size() < 1)
|
||||
{
|
||||
if (!discovery.IsComplete()) throw VolumeDiscoveryFailed (SRC_POS, wstring (discovery.UnresolvedMounts.front()));
|
||||
throw_err (_("No such volume is mounted."));
|
||||
}
|
||||
|
||||
return filteredVolumes;
|
||||
}
|
||||
|
||||
@@ -86,6 +86,7 @@ namespace VeraCrypt
|
||||
uint64 ArgSize;
|
||||
shared_ptr <VolumePath> ArgVolumePath;
|
||||
VolumeInfoList ArgVolumes;
|
||||
list <DirectoryPath> ArgUnresolvedMounts;
|
||||
VolumeType::Enum ArgVolumeType;
|
||||
shared_ptr<SecureBuffer> ArgTokenPin;
|
||||
bool ArgAllowScreencapture;
|
||||
@@ -103,7 +104,7 @@ namespace VeraCrypt
|
||||
protected:
|
||||
void CheckCommandSingle () const;
|
||||
shared_ptr <KeyfileList> ToKeyfileList (const wxString &arg) const;
|
||||
VolumeInfoList GetMountedVolumes (const wxString &filter) const;
|
||||
VolumeInfoList GetMountedVolumes (const wxString &filter);
|
||||
|
||||
private:
|
||||
CommandLineInterface (const CommandLineInterface &);
|
||||
|
||||
+211
-15
@@ -21,6 +21,7 @@
|
||||
|
||||
#include "Common/SecurityToken.h"
|
||||
#include "Platform/SystemLog.h"
|
||||
#include "Platform/SerializerFactory.h"
|
||||
#include "Main/Main.h"
|
||||
#include "Main/Resources.h"
|
||||
#include "Main/Application.h"
|
||||
@@ -38,12 +39,66 @@
|
||||
#include "SecurityTokenKeyfilesDialog.h"
|
||||
#include "VolumeCreationWizard.h"
|
||||
#include "VolumePropertiesDialog.h"
|
||||
#ifdef TC_MACOSX
|
||||
#include <chrono>
|
||||
#include "Core/Unix/MacOSX/CoreMacOSX.h"
|
||||
#endif
|
||||
|
||||
namespace VeraCrypt
|
||||
{
|
||||
#ifdef TC_MACOSX
|
||||
struct VolumeDiscoveryState
|
||||
{
|
||||
VolumeDiscoveryState (wxEvtHandler *target) : Running (false), Completed (false), Succeeded (false), HasResult (false), Generation (0), ResultGeneration (0), Started (chrono::steady_clock::now()), NotificationTarget (target)
|
||||
{
|
||||
// A kernel-blocked metadata read may outlive GUI shutdown. Retain the
|
||||
// read-only serializer registry until process exit as well as this state;
|
||||
// static teardown must not delete it underneath the detached worker.
|
||||
static const bool registryRetained = [] () { SerializerFactory::Initialize(); return true; } ();
|
||||
(void) registryRetained;
|
||||
}
|
||||
// Constructed on the GUI thread (CoreUnix initializes locale state).
|
||||
CoreMacOSX DiscoveryCore;
|
||||
Mutex AccessMutex;
|
||||
bool Running, Completed, Succeeded, HasResult;
|
||||
uint64 Generation, ResultGeneration;
|
||||
chrono::steady_clock::time_point Started;
|
||||
VolumeDiscoveryResult Result;
|
||||
wxEvtHandler *NotificationTarget;
|
||||
};
|
||||
|
||||
class VolumeDiscoveryTask : public Functor
|
||||
{
|
||||
public:
|
||||
VolumeDiscoveryTask (shared_ptr <VolumeDiscoveryState> state, uint64 generation) : State (state), Generation (generation) { }
|
||||
virtual void operator() ()
|
||||
{
|
||||
VolumeDiscoveryResult result;
|
||||
bool succeeded = false;
|
||||
try { result = State->DiscoveryCore.GetMountedVolumesWithStatus(); succeeded = true; }
|
||||
catch (exception &e) { SystemLog::WriteException (e); }
|
||||
catch (...) { }
|
||||
ScopeLock lock (State->AccessMutex);
|
||||
State->Result = result;
|
||||
State->Succeeded = succeeded;
|
||||
State->HasResult = true;
|
||||
State->ResultGeneration = Generation;
|
||||
State->Completed = true;
|
||||
State->Running = false;
|
||||
// Destruction clears this pointer under the same lock before the
|
||||
// window's event handler is destroyed. Never post to a dead window.
|
||||
if (State->NotificationTarget)
|
||||
wxQueueEvent (State->NotificationTarget, new wxCommandEvent (wxEVT_COMMAND_VOLUME_DISCOVERY_COMPLETED));
|
||||
}
|
||||
private:
|
||||
shared_ptr <VolumeDiscoveryState> State;
|
||||
uint64 Generation;
|
||||
};
|
||||
#endif
|
||||
DEFINE_EVENT_TYPE(wxEVT_COMMAND_UPDATE_VOLUME_LIST)
|
||||
DEFINE_EVENT_TYPE(wxEVT_COMMAND_PREF_UPDATED)
|
||||
DEFINE_EVENT_TYPE(wxEVT_COMMAND_OPEN_VOLUME_REQUEST)
|
||||
DEFINE_EVENT_TYPE(wxEVT_COMMAND_VOLUME_DISCOVERY_COMPLETED)
|
||||
DEFINE_EVENT_TYPE(wxEVT_COMMAND_SHOW_WARNING)
|
||||
|
||||
MainFrame::MainFrame (wxWindow* parent) : MainFrameBase (parent),
|
||||
@@ -56,6 +111,9 @@ namespace VeraCrypt
|
||||
indicator_item_exit (NULL),
|
||||
#endif
|
||||
ListItemRightClickEventPending (false),
|
||||
#ifdef TC_MACOSX
|
||||
VolumeDiscovery (new VolumeDiscoveryState (this)),
|
||||
#endif
|
||||
SelectedItemIndex (-1),
|
||||
SelectedSlotNumber (0),
|
||||
ShowRequestFifo (-1)
|
||||
@@ -65,6 +123,9 @@ namespace VeraCrypt
|
||||
SetName (Application::GetName());
|
||||
SetTitle (Application::GetName());
|
||||
SetIcon (Resources::GetVeraCryptIcon());
|
||||
#ifdef TC_MACOSX
|
||||
CreateStatusBar();
|
||||
#endif
|
||||
|
||||
#if defined(TC_UNIX) && !defined(TC_MACOSX)
|
||||
try
|
||||
@@ -105,7 +166,8 @@ namespace VeraCrypt
|
||||
}
|
||||
|
||||
Connect( wxID_EXIT, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrame::OnQuit ) );
|
||||
Connect( wxID_ANY, wxEVT_COMMAND_UPDATE_VOLUME_LIST, wxCommandEventHandler( MainFrame::OnUpdateVolumeList ) );
|
||||
Connect( wxID_ANY, wxEVT_COMMAND_UPDATE_VOLUME_LIST, wxThreadEventHandler( MainFrame::OnUpdateVolumeList ) );
|
||||
Connect( wxID_ANY, wxEVT_COMMAND_VOLUME_DISCOVERY_COMPLETED, wxCommandEventHandler( MainFrame::OnVolumeDiscoveryCompleted ) );
|
||||
Connect( wxID_ANY, wxEVT_COMMAND_PREF_UPDATED, wxCommandEventHandler( MainFrame::OnPreferencesUpdated ) );
|
||||
Connect( wxID_ANY, wxEVT_COMMAND_OPEN_VOLUME_REQUEST, wxCommandEventHandler( MainFrame::OnOpenVolumeSystemRequest ) );
|
||||
|
||||
@@ -116,6 +178,12 @@ namespace VeraCrypt
|
||||
|
||||
MainFrame::~MainFrame ()
|
||||
{
|
||||
#ifdef TC_MACOSX
|
||||
{
|
||||
ScopeLock lock (VolumeDiscovery->AccessMutex);
|
||||
VolumeDiscovery->NotificationTarget = nullptr;
|
||||
}
|
||||
#endif
|
||||
#if defined(TC_UNIX) && !defined(TC_MACOSX)
|
||||
if (ShowRequestFifo != -1)
|
||||
{
|
||||
@@ -129,7 +197,8 @@ namespace VeraCrypt
|
||||
#endif
|
||||
|
||||
Disconnect( wxID_EXIT, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrame::OnQuit ) );
|
||||
Disconnect( wxID_ANY, wxEVT_COMMAND_UPDATE_VOLUME_LIST, wxCommandEventHandler( MainFrame::OnUpdateVolumeList ) );
|
||||
Disconnect( wxID_ANY, wxEVT_COMMAND_UPDATE_VOLUME_LIST, wxThreadEventHandler( MainFrame::OnUpdateVolumeList ) );
|
||||
Disconnect( wxID_ANY, wxEVT_COMMAND_VOLUME_DISCOVERY_COMPLETED, wxCommandEventHandler( MainFrame::OnVolumeDiscoveryCompleted ) );
|
||||
Disconnect( wxID_ANY, wxEVT_COMMAND_PREF_UPDATED, wxCommandEventHandler( MainFrame::OnPreferencesUpdated ) );
|
||||
Disconnect( wxID_ANY, wxEVT_COMMAND_OPEN_VOLUME_REQUEST, wxCommandEventHandler( MainFrame::OnOpenVolumeSystemRequest ) );
|
||||
#ifdef TC_MACOSX
|
||||
@@ -268,9 +337,27 @@ namespace VeraCrypt
|
||||
}
|
||||
}
|
||||
|
||||
bool MainFrame::CanConfirmNoMountedVolumes () const
|
||||
{
|
||||
#ifdef TC_MACOSX
|
||||
// An unacknowledged unconfirmed cleanup must not disappear with the app.
|
||||
return VolumeSnapshot.CanConfirmEmpty (MountedVolumes.empty()) && !Gui->HasUnconfirmedCleanupWarnings();
|
||||
#else
|
||||
return MountedVolumes.empty();
|
||||
#endif
|
||||
}
|
||||
|
||||
shared_ptr <VolumeInfo> MainFrame::GetSelectedVolume () const
|
||||
{
|
||||
#ifdef TC_MACOSX
|
||||
// Keep selection tied to the displayed instance. Core operations validate
|
||||
// its serial and resolve current image ownership again before acting.
|
||||
foreach (shared_ptr <VolumeInfo> volume, MountedVolumes)
|
||||
if (volume->SlotNumber == SelectedSlotNumber) return volume;
|
||||
return shared_ptr <VolumeInfo>();
|
||||
#else
|
||||
return Core->GetMountedVolume (SelectedSlotNumber);
|
||||
#endif
|
||||
}
|
||||
|
||||
void MainFrame::InitControls ()
|
||||
@@ -530,12 +617,13 @@ namespace VeraCrypt
|
||||
wxMenu *CreatePopupMenu ()
|
||||
{
|
||||
unique_ptr <wxMenu> popup (new wxMenu);
|
||||
const bool operationsEnabled = !Busy && !Gui->GetWaitDialog();
|
||||
|
||||
Gui->AppendToMenu (*popup, LangString[Gui->IsInBackgroundMode() ? "SHOW_TC" : "HIDE_TC"], this, wxCommandEventHandler (TaskBarIcon::OnShowHideMenuItemSelected));
|
||||
|
||||
popup->AppendSeparator();
|
||||
Gui->AppendToMenu (*popup, LangString["IDM_MOUNT_FAVORITE_VOLUMES"], this, wxCommandEventHandler (TaskBarIcon::OnMountAllFavoritesMenuItemSelected))->Enable (!Busy);
|
||||
Gui->AppendToMenu (*popup, LangString["HK_UNMOUNT_ALL"], this, wxCommandEventHandler (TaskBarIcon::OnDismountAllMenuItemSelected))->Enable (!Busy);
|
||||
Gui->AppendToMenu (*popup, LangString["IDM_MOUNT_FAVORITE_VOLUMES"], this, wxCommandEventHandler (TaskBarIcon::OnMountAllFavoritesMenuItemSelected))->Enable (operationsEnabled);
|
||||
Gui->AppendToMenu (*popup, LangString["HK_UNMOUNT_ALL"], this, wxCommandEventHandler (TaskBarIcon::OnDismountAllMenuItemSelected))->Enable (operationsEnabled);
|
||||
|
||||
// Favorite volumes
|
||||
if (Gui->GetPreferences().BackgroundTaskMenuMountItemsEnabled && !Frame->FavoriteVolumesMenuMap.empty())
|
||||
@@ -546,12 +634,12 @@ namespace VeraCrypt
|
||||
{
|
||||
//TBH Gui->AppendToMenu (*popup, LangString["MOUNT"] + L" " + wstring (fp.second.Path) + (fp.second.MountPoint.IsEmpty() ? L"" : L" " + wstring (fp.second.MountPoint)),
|
||||
Gui->AppendToMenu (*popup, LangString["MOUNT_BUTTON"] + L" " + wstring (fp.second.Path) + (fp.second.MountPoint.IsEmpty() ? L"" : L" " + wstring (fp.second.MountPoint)),
|
||||
this, wxCommandEventHandler (TaskBarIcon::OnFavoriteVolumeMenuItemSelected), fp.first)->Enable (!Busy);
|
||||
this, wxCommandEventHandler (TaskBarIcon::OnFavoriteVolumeMenuItemSelected), fp.first)->Enable (operationsEnabled);
|
||||
}
|
||||
}
|
||||
|
||||
// Mounted volumes
|
||||
VolumeInfoList mountedVolumes = Core->GetMountedVolumes();
|
||||
VolumeInfoList mountedVolumes = Gui->GetMountedVolumesForUI();
|
||||
if (!mountedVolumes.empty())
|
||||
{
|
||||
if (Gui->GetPreferences().BackgroundTaskMenuOpenItemsEnabled)
|
||||
@@ -583,14 +671,14 @@ namespace VeraCrypt
|
||||
label += wstring (volume->Path);
|
||||
|
||||
wxMenuItem *item = Gui->AppendToMenu (*popup, label, this, wxCommandEventHandler (TaskBarIcon::OnDismountMenuItemSelected));
|
||||
item->Enable (!Busy);
|
||||
item->Enable (operationsEnabled);
|
||||
DismountMap[item->GetId()] = volume;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
popup->AppendSeparator();
|
||||
Gui->AppendToMenu (*popup, LangString["IDM_PREFERENCES"], this, wxCommandEventHandler (TaskBarIcon::OnPreferencesMenuItemSelected))->Enable (!Busy);
|
||||
Gui->AppendToMenu (*popup, LangString["IDM_PREFERENCES"], this, wxCommandEventHandler (TaskBarIcon::OnPreferencesMenuItemSelected))->Enable (operationsEnabled);
|
||||
#ifndef TC_MACOSX
|
||||
popup->AppendSeparator();
|
||||
Gui->AppendToMenu (*popup, LangString["EXIT"], this, wxCommandEventHandler (TaskBarIcon::OnExitMenuItemSelected))->Enable (!Busy && Frame->CanExit());
|
||||
@@ -808,6 +896,13 @@ namespace VeraCrypt
|
||||
|
||||
void MainFrame::OnClose (wxCloseEvent& event)
|
||||
{
|
||||
// Do not start another core operation from a nested wait event loop.
|
||||
if (Gui->GetWaitDialog())
|
||||
{
|
||||
if (event.CanVeto())
|
||||
event.Veto();
|
||||
return;
|
||||
}
|
||||
if (GetPreferences().WipeCacheOnClose)
|
||||
Core->WipePasswordCache();
|
||||
|
||||
@@ -816,7 +911,7 @@ namespace VeraCrypt
|
||||
{
|
||||
try
|
||||
{
|
||||
Gui->DismountVolumes (Core->GetMountedVolumes(), GetPreferences().ForceAutoDismount, false);
|
||||
Gui->OnLogOff();
|
||||
}
|
||||
catch (exception &e) { SystemLog::WriteException (e); }
|
||||
catch (...) { SystemLog::WriteException (UnknownException (SRC_POS)); }
|
||||
@@ -848,7 +943,7 @@ namespace VeraCrypt
|
||||
}
|
||||
}
|
||||
else if (event.CanVeto() && GetPreferences().BackgroundTaskEnabled
|
||||
&& (!GetPreferences().CloseBackgroundTaskOnNoVolumes || !MountedVolumes.empty()))
|
||||
&& (!GetPreferences().CloseBackgroundTaskOnNoVolumes || !CanConfirmNoMountedVolumes()))
|
||||
{
|
||||
// Enter background mode
|
||||
if (!Gui->IsInBackgroundMode())
|
||||
@@ -1377,18 +1472,37 @@ namespace VeraCrypt
|
||||
UpdateVolumeList();
|
||||
UpdateWipeCacheButton();
|
||||
|
||||
if (GetPreferences().BackgroundTaskEnabled)
|
||||
if (GetPreferences().BackgroundTaskEnabled && !Gui->GetWaitDialog())
|
||||
{
|
||||
// Inactivity auto-dismount
|
||||
if (GetPreferences().DismountOnInactivity)
|
||||
if (GetPreferences().DismountOnInactivity
|
||||
#ifdef TC_MACOSX
|
||||
&& VolumeSnapshot.IsFresh()
|
||||
#endif
|
||||
)
|
||||
{
|
||||
VolumeInfoList inactiveVolumes;
|
||||
#ifdef TC_MACOSX
|
||||
wxLongLong currentTime = chrono::duration_cast <chrono::milliseconds> (chrono::steady_clock::now().time_since_epoch()).count();
|
||||
#else
|
||||
wxLongLong currentTime = wxGetLocalTimeMillis().GetValue();
|
||||
#endif
|
||||
|
||||
map <wstring, VolumeActivityMapEntry> newActivityTimeMap;
|
||||
|
||||
foreach (shared_ptr <VolumeInfo> volume, MountedVolumes)
|
||||
{
|
||||
#ifdef TC_MACOSX
|
||||
// A retained entry has no current counters. Keep its idle state until
|
||||
// they can be read again: unchanged cumulative counters prove idleness.
|
||||
if (volume->Discovery == VolumeInfo::ControlUnavailable)
|
||||
{
|
||||
map <wstring, VolumeActivityMapEntry>::const_iterator entry = VolumeActivityMap.find (volume->Path);
|
||||
if (entry != VolumeActivityMap.end() && entry->second.SerialInstanceNumber == volume->SerialInstanceNumber)
|
||||
newActivityTimeMap[volume->Path] = entry->second;
|
||||
continue;
|
||||
}
|
||||
#endif
|
||||
if (VolumeActivityMap.find (volume->Path) != VolumeActivityMap.end()
|
||||
&& VolumeActivityMap[volume->Path].SerialInstanceNumber == volume->SerialInstanceNumber)
|
||||
{
|
||||
@@ -1447,7 +1561,8 @@ namespace VeraCrypt
|
||||
{
|
||||
Close (true);
|
||||
}
|
||||
else if (MountedVolumes.empty() && (GetPreferences().CloseBackgroundTaskOnNoVolumes || Core->IsInPortableMode()))
|
||||
else if (CanConfirmNoMountedVolumes()
|
||||
&& (GetPreferences().CloseBackgroundTaskOnNoVolumes || Core->IsInPortableMode()))
|
||||
{
|
||||
Close (true);
|
||||
}
|
||||
@@ -1683,19 +1798,94 @@ namespace VeraCrypt
|
||||
UpdateWipeCacheButton();
|
||||
}
|
||||
|
||||
void MainFrame::UpdateVolumeList ()
|
||||
void MainFrame::OnUpdateVolumeList (wxThreadEvent& event)
|
||||
{
|
||||
#ifdef TC_MACOSX
|
||||
{
|
||||
ScopeLock lock (VolumeDiscovery->AccessMutex);
|
||||
++VolumeDiscovery->Generation;
|
||||
}
|
||||
VolumeSnapshot.Invalidate();
|
||||
VolumeListChange change = event.GetPayload <VolumeListChange>();
|
||||
MountedVolumes.remove_if ([&change] (shared_ptr <VolumeInfo> volume) { return volume->SerialInstanceNumber == change.Volume->SerialInstanceNumber; });
|
||||
if (change.Mounted) MountedVolumes.push_back (change.Volume);
|
||||
#endif
|
||||
UpdateVolumeList();
|
||||
}
|
||||
|
||||
void MainFrame::OnVolumeDiscoveryCompleted (wxCommandEvent& event)
|
||||
{
|
||||
try { UpdateVolumeList (false); }
|
||||
catch (exception &e) { SystemLog::WriteException (e); }
|
||||
catch (...) { }
|
||||
}
|
||||
|
||||
void MainFrame::UpdateVolumeList (bool startDiscovery)
|
||||
{
|
||||
static Mutex mutex;
|
||||
ScopeLock lock (mutex);
|
||||
|
||||
bool listChanged = false;
|
||||
|
||||
#ifdef TC_MACOSX
|
||||
{
|
||||
ScopeLock discoveryLock (VolumeDiscovery->AccessMutex);
|
||||
auto now = chrono::steady_clock::now();
|
||||
if (VolumeDiscovery->Completed)
|
||||
{
|
||||
if (VolumeDiscovery->Succeeded && VolumeDiscovery->ResultGeneration == VolumeDiscovery->Generation)
|
||||
{
|
||||
VolumeDiscoveryResult &result = VolumeDiscovery->Result;
|
||||
// Retain the identity of previously seen but now unreadable services.
|
||||
// New unresolved candidates remain separate, without invented slots.
|
||||
foreach (shared_ptr <VolumeInfo> old, MountedVolumes)
|
||||
if (find (result.UnresolvedMounts.begin(), result.UnresolvedMounts.end(), old->AuxMountPoint) != result.UnresolvedMounts.end()
|
||||
&& none_of (result.Volumes.begin(), result.Volumes.end(), [&old] (shared_ptr <VolumeInfo> volume) { return volume->SerialInstanceNumber == old->SerialInstanceNumber; }))
|
||||
{
|
||||
shared_ptr <VolumeInfo> unknown = old->Clone();
|
||||
unknown->Discovery = VolumeInfo::ControlUnavailable;
|
||||
unknown->VirtualDevice = DevicePath();
|
||||
unknown->MountPoint = DirectoryPath();
|
||||
result.Volumes.push_back (unknown);
|
||||
}
|
||||
MountedVolumes.swap (result.Volumes);
|
||||
VolumeSnapshot.RecordSample (VolumeDiscovery->Started, result.IsComplete());
|
||||
}
|
||||
else
|
||||
{
|
||||
VolumeSnapshot.Invalidate();
|
||||
// A volume event invalidated an in-flight result. Start the
|
||||
// replacement immediately, without waiting for the next timer.
|
||||
if (VolumeDiscovery->ResultGeneration != VolumeDiscovery->Generation) startDiscovery = true;
|
||||
}
|
||||
VolumeDiscovery->Completed = false;
|
||||
}
|
||||
bool stale = !VolumeSnapshot.IsFresh (now);
|
||||
SetStatusText (stale ? LangString[!VolumeDiscovery->HasResult && now - VolumeDiscovery->Started < chrono::seconds (6)
|
||||
? "VOLUME_DISCOVERY_PENDING" : "VOLUME_DISCOVERY_STALLED"]
|
||||
: (VolumeSnapshot.IsComplete() ? wxString() : LangString["VOLUME_DISCOVERY_PARTIAL"]));
|
||||
if (startDiscovery && !VolumeDiscovery->Running)
|
||||
{
|
||||
VolumeDiscovery->Started = now;
|
||||
VolumeDiscovery->Running = true;
|
||||
unique_ptr <Functor> task (new VolumeDiscoveryTask (VolumeDiscovery, VolumeDiscovery->Generation));
|
||||
Thread thread;
|
||||
try { thread.Start (task.get()); }
|
||||
catch (...) { VolumeDiscovery->Running = false; throw; }
|
||||
task.release();
|
||||
thread.Detach();
|
||||
}
|
||||
}
|
||||
#else
|
||||
MountedVolumes = Core->GetMountedVolumes();
|
||||
#endif
|
||||
|
||||
map < VolumeSlotNumber, shared_ptr <VolumeInfo> > mountedVolumesMap;
|
||||
foreach (shared_ptr <VolumeInfo> volume, MountedVolumes)
|
||||
{
|
||||
mountedVolumesMap[volume->SlotNumber] = volume;
|
||||
// A live replacement may share a slot with a retained unreadable entry.
|
||||
// Keep the visible row and selection on the first (live) instance.
|
||||
mountedVolumesMap.insert (make_pair (volume->SlotNumber, volume));
|
||||
}
|
||||
|
||||
VolumeInfoList protectionTriggeredVolumes;
|
||||
@@ -1717,6 +1907,12 @@ namespace VeraCrypt
|
||||
#else
|
||||
fields[ColumnSlot] = StringConverter::FromNumber (slotNumber);
|
||||
fields[ColumnMountPoint] = volume->MountPoint;
|
||||
#ifdef TC_MACOSX
|
||||
if (volume->Discovery == VolumeInfo::DiscoveryUnknown || volume->Discovery == VolumeInfo::ControlUnavailable)
|
||||
fields[ColumnMountPoint] = LangString["VOLUME_STATUS_UNKNOWN"];
|
||||
else if (volume->Discovery == VolumeInfo::ImageAbsent)
|
||||
fields[ColumnMountPoint] = LangString["VOLUME_IMAGE_ABSENT"];
|
||||
#endif
|
||||
#endif
|
||||
fields[ColumnPath] = volume->Path;
|
||||
fields[ColumnSize] = Gui->SizeToString (volume->Size);
|
||||
|
||||
@@ -23,15 +23,26 @@
|
||||
#include "ChangePasswordDialog.h"
|
||||
#ifdef TC_MACOSX
|
||||
#include <wx/display.h>
|
||||
#include "Main/VolumeSnapshot.h"
|
||||
#endif
|
||||
|
||||
namespace VeraCrypt
|
||||
{
|
||||
struct FavoriteVolume;
|
||||
#ifdef TC_MACOSX
|
||||
struct VolumeDiscoveryState;
|
||||
#endif
|
||||
|
||||
DECLARE_LOCAL_EVENT_TYPE(wxEVT_COMMAND_UPDATE_VOLUME_LIST, -1);
|
||||
DECLARE_LOCAL_EVENT_TYPE(wxEVT_COMMAND_PREF_UPDATED, -1);
|
||||
DECLARE_LOCAL_EVENT_TYPE(wxEVT_COMMAND_OPEN_VOLUME_REQUEST, -1);
|
||||
DECLARE_LOCAL_EVENT_TYPE(wxEVT_COMMAND_VOLUME_DISCOVERY_COMPLETED, -1);
|
||||
|
||||
struct VolumeListChange
|
||||
{
|
||||
bool Mounted;
|
||||
shared_ptr <VolumeInfo> Volume;
|
||||
};
|
||||
|
||||
class MainFrame : public MainFrameBase
|
||||
{
|
||||
@@ -45,6 +56,11 @@ namespace VeraCrypt
|
||||
#endif
|
||||
|
||||
void MountAllFavorites ();
|
||||
VolumeInfoList GetDisplayedVolumes () const { return MountedVolumes; }
|
||||
#ifdef TC_MACOSX
|
||||
bool HasVolumeSnapshot () const { return VolumeSnapshot.HasSample(); }
|
||||
#endif
|
||||
bool CanConfirmNoMountedVolumes () const;
|
||||
|
||||
#ifdef HAVE_INDICATORS
|
||||
AppIndicator *indicator;
|
||||
@@ -167,9 +183,17 @@ namespace VeraCrypt
|
||||
void OnVolumePropertiesButtonClick (wxCommandEvent& event);
|
||||
void OnVolumeToolsButtonClick (wxCommandEvent& event);
|
||||
void OnVolumeButtonClick (wxCommandEvent& event);
|
||||
void OnUpdateVolumeList (wxCommandEvent& event) { UpdateVolumeList(); }
|
||||
void OnVolumeDismounted (EventArgs &args) { wxQueueEvent (this, new wxCommandEvent( wxEVT_COMMAND_UPDATE_VOLUME_LIST,0)); }
|
||||
void OnVolumeMounted (EventArgs &args) { wxQueueEvent (this, new wxCommandEvent( wxEVT_COMMAND_UPDATE_VOLUME_LIST,0)); }
|
||||
void OnUpdateVolumeList (wxThreadEvent& event);
|
||||
void OnVolumeDiscoveryCompleted (wxCommandEvent& event);
|
||||
void OnVolumeChange (EventArgs &args, bool mounted)
|
||||
{
|
||||
wxThreadEvent *event = new wxThreadEvent (wxEVT_COMMAND_UPDATE_VOLUME_LIST);
|
||||
VolumeListChange change = { mounted, static_cast <VolumeEventArgs &> (args).mVolume->Clone() };
|
||||
event->SetPayload (change);
|
||||
wxQueueEvent (this, event);
|
||||
}
|
||||
void OnVolumeDismounted (EventArgs &args) { OnVolumeChange (args, false); }
|
||||
void OnVolumeMounted (EventArgs &args) { OnVolumeChange (args, true); }
|
||||
void OnUserGuideMenuItemSelected (wxCommandEvent& event) { Gui->OpenUserGuide (this); }
|
||||
void OnWebsiteMenuItemSelected (wxCommandEvent& event) { Gui->OpenHomepageLink (this, L"website"); }
|
||||
void OnWipeCacheButtonClick (wxCommandEvent& event);
|
||||
@@ -180,7 +204,7 @@ namespace VeraCrypt
|
||||
void SetVolumePath (const VolumePath &path) { VolumePathComboBox->SetValue (wstring (path)); }
|
||||
void ShowTaskBarIcon (bool show = true);
|
||||
void UpdateControls ();
|
||||
void UpdateVolumeList ();
|
||||
void UpdateVolumeList (bool startDiscovery = true);
|
||||
void UpdateWipeCacheButton ();
|
||||
void WipeCache ();
|
||||
|
||||
@@ -233,6 +257,10 @@ namespace VeraCrypt
|
||||
map <int, FavoriteVolume> FavoriteVolumesMenuMap;
|
||||
bool ListItemRightClickEventPending;
|
||||
VolumeInfoList MountedVolumes;
|
||||
#ifdef TC_MACOSX
|
||||
shared_ptr <VolumeDiscoveryState> VolumeDiscovery;
|
||||
VolumeSnapshotState VolumeSnapshot;
|
||||
#endif
|
||||
unique_ptr <wxTaskBarIcon> mTaskBarIcon;
|
||||
unique_ptr <wxTimer> mTimer;
|
||||
long SelectedItemIndex;
|
||||
|
||||
@@ -60,6 +60,9 @@ namespace VeraCrypt
|
||||
VC_CONVERT_EXCEPTION (MountPointUnavailable);
|
||||
VC_CONVERT_EXCEPTION (MountServiceIncompatible);
|
||||
VC_CONVERT_EXCEPTION (MountServiceCleanupFailed);
|
||||
VC_CONVERT_EXCEPTION (DismountServiceCleanupFailed);
|
||||
VC_CONVERT_EXCEPTION (MountServiceUnavailable);
|
||||
VC_CONVERT_EXCEPTION (VolumeDiscoveryFailed);
|
||||
VC_CONVERT_EXCEPTION (NoDriveLetterAvailable);
|
||||
VC_CONVERT_EXCEPTION (TemporaryDirectoryFailure);
|
||||
VC_CONVERT_EXCEPTION (UnsupportedSectorSizeHiddenVolumeProtection);
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
*/
|
||||
|
||||
#include "System.h"
|
||||
#include <chrono>
|
||||
|
||||
#ifdef TC_UNIX
|
||||
#include <wx/mimetype.h>
|
||||
@@ -121,7 +122,9 @@ namespace VeraCrypt
|
||||
{
|
||||
|
||||
wxString sValue;
|
||||
if (Gui->GetWaitDialog())
|
||||
// Only a worker can wait for the dialog's queue. The main thread
|
||||
// would block on a reply that only it could deliver.
|
||||
if (Gui->GetWaitDialog() && !wxIsMainThread())
|
||||
{
|
||||
Gui->GetWaitDialog()->RequestAdminPassword(sValue);
|
||||
if (sValue.IsEmpty())
|
||||
@@ -163,6 +166,9 @@ namespace VeraCrypt
|
||||
BackgroundMode (false),
|
||||
mMainFrame (nullptr),
|
||||
mWaitDialog (nullptr)
|
||||
#ifdef TC_MACOSX
|
||||
, mShowingCleanupWarning (false)
|
||||
#endif
|
||||
{
|
||||
#ifdef TC_UNIX
|
||||
signal (SIGHUP, OnSignal);
|
||||
@@ -229,7 +235,17 @@ namespace VeraCrypt
|
||||
|
||||
void GraphicUserInterface::AutoDismountVolumes (VolumeInfoList mountedVolumes, bool alwaysForce)
|
||||
{
|
||||
#ifdef TC_MACOSX
|
||||
if (mountedVolumes.empty() || GetWaitDialog())
|
||||
return;
|
||||
// An automatic lock request must not leave cached credentials behind
|
||||
// merely because service exit confirmation is delayed or fails.
|
||||
try { OnVolumesAutoDismounted(); }
|
||||
catch (exception &e) { SystemLog::WriteException (e); }
|
||||
catch (...) { }
|
||||
#else
|
||||
size_t mountedVolumeCount = Core->GetMountedVolumes().size();
|
||||
#endif
|
||||
try
|
||||
{
|
||||
wxBusyCursor busy;
|
||||
@@ -237,9 +253,10 @@ namespace VeraCrypt
|
||||
}
|
||||
catch (exception &e) { SystemLog::WriteException (e); }
|
||||
catch (...) { SystemLog::WriteException (UnknownException (SRC_POS)); }
|
||||
|
||||
#ifndef TC_MACOSX
|
||||
if (Core->GetMountedVolumes().size() < mountedVolumeCount)
|
||||
OnVolumesAutoDismounted();
|
||||
#endif
|
||||
}
|
||||
|
||||
void GraphicUserInterface::BackupVolumeHeaders (shared_ptr <VolumePath> volumePath) const
|
||||
@@ -700,7 +717,7 @@ namespace VeraCrypt
|
||||
throw MissingArgument (SRC_POS);
|
||||
|
||||
wxString sValue;
|
||||
if (Gui->GetWaitDialog())
|
||||
if (Gui->GetWaitDialog() && !wxIsMainThread())
|
||||
{
|
||||
sValue = StringConverter::ToWide (passwordStr).c_str();
|
||||
Gui->GetWaitDialog()->RequestPin (sValue);
|
||||
@@ -1308,8 +1325,86 @@ namespace VeraCrypt
|
||||
return true;
|
||||
}
|
||||
|
||||
#ifdef TC_MACOSX
|
||||
VolumeInfoList GraphicUserInterface::GetVolumesForAutoDismount () const
|
||||
{
|
||||
VolumeInfoList volumes = GetMountedVolumesForUI();
|
||||
try
|
||||
{
|
||||
VolumeDiscoveryResult result = Core->GetMountedVolumesWithStatus();
|
||||
VolumeInfoList captured;
|
||||
captured.swap (volumes);
|
||||
volumes = result.Volumes;
|
||||
foreach (shared_ptr <VolumeInfo> volume, captured)
|
||||
if (find (result.UnresolvedMounts.begin(), result.UnresolvedMounts.end(), volume->AuxMountPoint) != result.UnresolvedMounts.end()
|
||||
&& none_of (volumes.begin(), volumes.end(), [&volume] (shared_ptr <VolumeInfo> current) { return current->SerialInstanceNumber == volume->SerialInstanceNumber; }))
|
||||
volumes.push_back (volume);
|
||||
if (!result.IsComplete()) SystemLog::WriteException (VolumeDiscoveryFailed (SRC_POS, wstring (result.UnresolvedMounts.front())));
|
||||
}
|
||||
catch (exception &e) { SystemLog::WriteException (e); }
|
||||
return volumes;
|
||||
}
|
||||
|
||||
void GraphicUserInterface::ReportUnconfirmedCleanup (const exception &e) const
|
||||
{
|
||||
// Without its auxiliary mount, the volume is no longer listed. Queue the
|
||||
// warning so that the reporting caller, such as the inactivity timer,
|
||||
// returns first and other volumes can still be unmounted automatically.
|
||||
mUnconfirmedCleanupWarnings.push_back (ExceptionToMessage (e));
|
||||
wxTheApp->CallAfter ([] () { Gui->ShowUnconfirmedCleanupWarnings(); });
|
||||
}
|
||||
|
||||
void GraphicUserInterface::ShowUnconfirmedCleanupWarnings () const
|
||||
{
|
||||
// One warning at a time; the active call also shows warnings added meanwhile.
|
||||
// Entries are removed only after acknowledgement, which prevents automatic exit.
|
||||
if (mShowingCleanupWarning)
|
||||
return;
|
||||
mShowingCleanupWarning = true;
|
||||
finally_do_arg (bool *, &mShowingCleanupWarning, { *finally_arg = false; });
|
||||
while (!mUnconfirmedCleanupWarnings.empty())
|
||||
{
|
||||
ShowWarningTopMost (mUnconfirmedCleanupWarnings.front());
|
||||
mUnconfirmedCleanupWarnings.pop_front();
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
void GraphicUserInterface::OnLogOff ()
|
||||
{
|
||||
#ifdef TC_MACOSX
|
||||
// This is also called directly by Cocoa. No exception may escape the
|
||||
// native callback, including before the first display snapshot exists.
|
||||
try
|
||||
{
|
||||
if (!GetPreferences().DismountOnLogOff || GetWaitDialog()) return;
|
||||
try { OnVolumesAutoDismounted(); }
|
||||
catch (exception &e) { SystemLog::WriteException (e); }
|
||||
catch (...) { }
|
||||
VolumeInfoList remaining = GetVolumesForAutoDismount();
|
||||
|
||||
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds (4);
|
||||
while (!remaining.empty())
|
||||
{
|
||||
bool finalAttempt = std::chrono::steady_clock::now() >= deadline;
|
||||
VolumeInfoList retry;
|
||||
foreach (shared_ptr <VolumeInfo> volume, remaining)
|
||||
{
|
||||
try { DismountVolume (volume, finalAttempt && GetPreferences().ForceAutoDismount, false); }
|
||||
// Without its auxiliary mount, another attempt cannot reach the service.
|
||||
catch (DismountServiceCleanupFailed &e) { SystemLog::WriteException (e); }
|
||||
catch (exception &e) { SystemLog::WriteException (e); retry.push_back (volume); }
|
||||
}
|
||||
remaining.swap (retry);
|
||||
if (finalAttempt || remaining.empty()) break;
|
||||
Thread::Sleep (500);
|
||||
}
|
||||
// A queued warning would never run once termination proceeds.
|
||||
ShowUnconfirmedCleanupWarnings();
|
||||
}
|
||||
catch (exception &e) { SystemLog::WriteException (e); }
|
||||
catch (...) { }
|
||||
#else
|
||||
VolumeInfoList mountedVolumes = Core->GetMountedVolumes();
|
||||
if (GetPreferences().BackgroundTaskEnabled && GetPreferences().DismountOnLogOff
|
||||
&& !mountedVolumes.empty())
|
||||
@@ -1338,10 +1433,11 @@ namespace VeraCrypt
|
||||
Thread::Sleep (500);
|
||||
}
|
||||
|
||||
VolumeInfoList mountedVolumes = Core->GetMountedVolumes();
|
||||
mountedVolumes = Core->GetMountedVolumes();
|
||||
}
|
||||
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef wxHAS_POWER_EVENTS
|
||||
@@ -2036,6 +2132,7 @@ namespace VeraCrypt
|
||||
|
||||
void GraphicUserInterface::SetBackgroundMode (bool state)
|
||||
{
|
||||
if (!mMainFrame) return;
|
||||
#ifdef TC_MACOSX
|
||||
// Hiding an iconized window on OS X apparently cannot be reversed
|
||||
if (state && mMainFrame->IsIconized())
|
||||
@@ -2210,7 +2307,7 @@ namespace VeraCrypt
|
||||
caption.clear();
|
||||
}
|
||||
#endif
|
||||
if (mWaitDialog)
|
||||
if (mWaitDialog && !wxIsMainThread())
|
||||
{
|
||||
return mWaitDialog->RequestShowMessage(subMessage, caption, style, topMost);
|
||||
}
|
||||
@@ -2218,7 +2315,7 @@ namespace VeraCrypt
|
||||
{
|
||||
if (topMost)
|
||||
{
|
||||
if (!IsActive())
|
||||
if (!IsActive() && mMainFrame)
|
||||
mMainFrame->RequestUserAttention (wxUSER_ATTENTION_ERROR);
|
||||
|
||||
style |= wxSTAY_ON_TOP;
|
||||
@@ -2304,11 +2401,79 @@ namespace VeraCrypt
|
||||
return routine.m_pVolume;
|
||||
}
|
||||
|
||||
VolumeInfoList GraphicUserInterface::GetMountedVolumesForUI () const
|
||||
{
|
||||
#ifdef TC_MACOSX
|
||||
if (mMainFrame)
|
||||
{
|
||||
MainFrame *frame = static_cast <MainFrame *> (mMainFrame.get());
|
||||
return frame->GetDisplayedVolumes();
|
||||
}
|
||||
return VolumeInfoList();
|
||||
#else
|
||||
return Core->GetMountedVolumes();
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef TC_MACOSX
|
||||
shared_ptr <VolumeInfo> GraphicUserInterface::DismountVolumeThread (shared_ptr <VolumeInfo> volume, bool ignoreOpenFiles, bool interactive) const
|
||||
{
|
||||
if (!interactive)
|
||||
{
|
||||
// Automatic unmounts run synchronously, as before. A quit or logout
|
||||
// request that arrives meanwhile is then handled afterwards; a hidden
|
||||
// wait's modal session would make macOS refuse it.
|
||||
try
|
||||
{
|
||||
return Core->DismountVolume (volume, ignoreOpenFiles);
|
||||
}
|
||||
catch (DismountServiceCleanupFailed &e)
|
||||
{
|
||||
ReportUnconfirmedCleanup (e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
class DismountRoutine : public WaitThreadRoutine
|
||||
{
|
||||
public:
|
||||
DismountRoutine (shared_ptr <VolumeInfo> volume, bool force) : Volume (volume), Force (force) { }
|
||||
virtual void ExecutionCode () { Volume = Core->DismountVolume (Volume, Force); }
|
||||
shared_ptr <VolumeInfo> Volume;
|
||||
bool Force;
|
||||
} routine (volume, ignoreOpenFiles);
|
||||
ExecuteWaitThreadRoutine (GetTopWindow(), &routine);
|
||||
return routine.Volume;
|
||||
}
|
||||
|
||||
void GraphicUserInterface::DismountAllVolumes (bool ignoreOpenFiles, bool interactive) const
|
||||
{
|
||||
class DiscoveryRoutine : public WaitThreadRoutine
|
||||
{
|
||||
public:
|
||||
virtual void ExecutionCode () { Result = Core->GetMountedVolumesWithStatus(); }
|
||||
VolumeDiscoveryResult Result;
|
||||
} routine;
|
||||
try
|
||||
{
|
||||
if (interactive)
|
||||
ExecuteWaitThreadRoutine (GetTopWindow(), &routine);
|
||||
else
|
||||
routine.ExecutionCode();
|
||||
if (interactive && routine.Result.Volumes.empty() && routine.Result.IsComplete()) ShowInfo (LangString["NO_VOLUMES_MOUNTED"]);
|
||||
DismountVolumes (routine.Result.Volumes, ignoreOpenFiles, interactive);
|
||||
if (!routine.Result.IsComplete()) throw VolumeDiscoveryFailed (SRC_POS, wstring (routine.Result.UnresolvedMounts.front()));
|
||||
}
|
||||
catch (exception &e) { if (interactive) ShowError (e); else SystemLog::WriteException (e); }
|
||||
}
|
||||
#endif
|
||||
|
||||
void GraphicUserInterface::ExecuteWaitThreadRoutine (wxWindow *parent, WaitThreadRoutine *pRoutine) const
|
||||
{
|
||||
WaitDialog dlg(parent, LangString["IDT_STATIC_MODAL_WAIT_DLG_INFO"], pRoutine);
|
||||
// Restore an outer wait, whose worker may still route requests through it.
|
||||
finally_do_arg2 (WaitDialog**, &mWaitDialog, WaitDialog*, mWaitDialog, { *finally_arg = finally_arg2; });
|
||||
mWaitDialog = &dlg;
|
||||
finally_do_arg (WaitDialog**, &mWaitDialog, { *finally_arg = nullptr; });
|
||||
dlg.Run();
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,9 @@
|
||||
#include "Main.h"
|
||||
#include "UserInterface.h"
|
||||
#include "Forms/WaitDialog.h"
|
||||
#ifdef TC_MACOSX
|
||||
#include <wx/weakref.h>
|
||||
#endif
|
||||
|
||||
namespace VeraCrypt
|
||||
{
|
||||
@@ -97,6 +100,13 @@ namespace VeraCrypt
|
||||
virtual void UserEnrichRandomPool (wxWindow *parent, shared_ptr <Hash> hash = shared_ptr <Hash>()) const;
|
||||
virtual void Yield () const;
|
||||
virtual shared_ptr <VolumeInfo> MountVolumeThread (MountOptions &options) const;
|
||||
#ifdef TC_MACOSX
|
||||
virtual shared_ptr <VolumeInfo> DismountVolumeThread (shared_ptr <VolumeInfo> volume, bool ignoreOpenFiles, bool interactive = true) const;
|
||||
virtual void DismountAllVolumes (bool ignoreOpenFiles = false, bool interactive = true) const;
|
||||
bool HasUnconfirmedCleanupWarnings () const { return !mUnconfirmedCleanupWarnings.empty(); }
|
||||
void ShowUnconfirmedCleanupWarnings () const;
|
||||
#endif
|
||||
VolumeInfoList GetMountedVolumesForUI () const;
|
||||
WaitDialog* GetWaitDialog () { return mWaitDialog; }
|
||||
void ExecuteWaitThreadRoutine (wxWindow *parent, WaitThreadRoutine *pRoutine) const;
|
||||
|
||||
@@ -127,6 +137,10 @@ namespace VeraCrypt
|
||||
#endif
|
||||
static void OnSignal (int signal);
|
||||
virtual void OnVolumesAutoDismounted ();
|
||||
#ifdef TC_MACOSX
|
||||
VolumeInfoList GetVolumesForAutoDismount () const;
|
||||
void ReportUnconfirmedCleanup (const exception &e) const;
|
||||
#endif
|
||||
virtual int ShowMessage (const wxString &message, long style, bool topMost = false) const;
|
||||
void ThrowTextModeRequired () const;
|
||||
|
||||
@@ -135,10 +149,18 @@ namespace VeraCrypt
|
||||
#ifdef TC_WINDOWS
|
||||
unique_ptr <wxDDEServer> DDEServer;
|
||||
#endif
|
||||
#ifdef TC_MACOSX
|
||||
wxWeakRef <wxFrame> mMainFrame;
|
||||
#else
|
||||
wxFrame *mMainFrame;
|
||||
#endif
|
||||
unique_ptr <wxSingleInstanceChecker> SingleInstanceChecker;
|
||||
|
||||
mutable WaitDialog* mWaitDialog;
|
||||
#ifdef TC_MACOSX
|
||||
mutable list <wxString> mUnconfirmedCleanupWarnings;
|
||||
mutable bool mShowingCleanupWarning;
|
||||
#endif
|
||||
public:
|
||||
#ifdef TC_MACOSX
|
||||
static int g_customIdCmdV;
|
||||
|
||||
+134
-80
@@ -184,6 +184,20 @@ namespace VeraCrypt
|
||||
DismountVolumes (volumes, ignoreOpenFiles, interactive);
|
||||
}
|
||||
|
||||
// Unconfirmed service exits are reported together, followed by any other
|
||||
// failure of the same operation, so that none of them can hide another.
|
||||
static void ThrowUnconfirmedCleanups (const list <DismountServiceCleanupFailed> &failures, const wstring &otherFailure)
|
||||
{
|
||||
wstring details;
|
||||
for (const DismountServiceCleanupFailed &failure : failures)
|
||||
details += (details.empty() ? L"" : L"\n\n") + failure.GetSubject();
|
||||
|
||||
if (!otherFailure.empty())
|
||||
details += L"\n\n" + otherFailure;
|
||||
|
||||
throw DismountServiceCleanupFailed (failures.front().what(), details);
|
||||
}
|
||||
|
||||
void UserInterface::DismountVolumes (VolumeInfoList volumes, bool ignoreOpenFiles, bool interactive, bool emergencyCleanupRequested) const
|
||||
{
|
||||
#ifndef TC_LINUX
|
||||
@@ -197,6 +211,9 @@ namespace VeraCrypt
|
||||
bool twoPassMode = volumes.size() > 1;
|
||||
bool volumesInUse = false;
|
||||
bool firstPass = true;
|
||||
// Such volumes have already left discovery. Report every one of them, even
|
||||
// when another volume fails or a forced-unmount prompt is declined.
|
||||
list <DismountServiceCleanupFailed> unconfirmedCleanups;
|
||||
|
||||
#ifdef TC_WINDOWS
|
||||
if (Preferences.CloseExplorerWindowsOnDismount)
|
||||
@@ -205,60 +222,51 @@ namespace VeraCrypt
|
||||
CloseExplorerWindows (volume);
|
||||
}
|
||||
#endif
|
||||
while (!volumes.empty())
|
||||
try
|
||||
{
|
||||
VolumeInfoList volumesLeft;
|
||||
foreach (shared_ptr <VolumeInfo> volume, volumes)
|
||||
while (!volumes.empty())
|
||||
{
|
||||
bool emergencyCleanupPerformed = false;
|
||||
try
|
||||
VolumeInfoList volumesLeft;
|
||||
foreach (shared_ptr <VolumeInfo> volume, volumes)
|
||||
{
|
||||
BusyScope busy (this);
|
||||
volume = Core->DismountVolume (volume, ignoreOpenFiles);
|
||||
}
|
||||
catch (MountedVolumeInUse&)
|
||||
{
|
||||
if (!firstPass || (!interactive && !twoPassMode))
|
||||
throw;
|
||||
|
||||
if (twoPassMode || !interactive)
|
||||
bool emergencyCleanupPerformed = false;
|
||||
try
|
||||
{
|
||||
volumesInUse = true;
|
||||
volumesLeft.push_back (volume);
|
||||
continue;
|
||||
BusyScope busy (this);
|
||||
volume = DismountVolumeThread (volume, ignoreOpenFiles, interactive);
|
||||
}
|
||||
else
|
||||
catch (MountedVolumeInUse&)
|
||||
{
|
||||
if (AskYesNo (StringFormatter (LangString["UNMOUNT_LOCK_FAILED"], wstring (volume->Path)), true, true))
|
||||
if (!firstPass || (!interactive && !twoPassMode))
|
||||
throw;
|
||||
|
||||
if (twoPassMode || !interactive)
|
||||
{
|
||||
BusyScope busy (this);
|
||||
volume = Core->DismountVolume (volume, true);
|
||||
volumesInUse = true;
|
||||
volumesLeft.push_back (volume);
|
||||
continue;
|
||||
}
|
||||
else
|
||||
throw UserAbort (SRC_POS);
|
||||
}
|
||||
}
|
||||
#ifdef TC_LINUX
|
||||
catch (FilesystemDismountFailed&)
|
||||
{
|
||||
if (twoPassMode && firstPass)
|
||||
{
|
||||
volumesLeft.push_back (volume);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (emergencyCleanupRequested)
|
||||
{
|
||||
{
|
||||
BusyScope busy (this);
|
||||
volume = Core->EmergencyDismountVolume (volume);
|
||||
if (AskYesNo (StringFormatter (LangString["UNMOUNT_LOCK_FAILED"], wstring (volume->Path)), true, true))
|
||||
{
|
||||
BusyScope busy (this);
|
||||
volume = DismountVolumeThread (volume, true);
|
||||
}
|
||||
else
|
||||
throw UserAbort (SRC_POS);
|
||||
}
|
||||
emergencyCleanupPerformed = true;
|
||||
ShowWarning (StringFormatter (LangString["LINUX_EMERGENCY_UNMOUNTED"], wstring (volume->Path)));
|
||||
}
|
||||
else if (interactive)
|
||||
#ifdef TC_LINUX
|
||||
catch (FilesystemDismountFailed&)
|
||||
{
|
||||
if (AskYesNo (StringFormatter (LangString["LINUX_EMERGENCY_UNMOUNT_WARNING"], wstring (volume->Path)), false, true))
|
||||
if (twoPassMode && firstPass)
|
||||
{
|
||||
volumesLeft.push_back (volume);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (emergencyCleanupRequested)
|
||||
{
|
||||
{
|
||||
BusyScope busy (this);
|
||||
@@ -267,55 +275,88 @@ namespace VeraCrypt
|
||||
emergencyCleanupPerformed = true;
|
||||
ShowWarning (StringFormatter (LangString["LINUX_EMERGENCY_UNMOUNTED"], wstring (volume->Path)));
|
||||
}
|
||||
else if (interactive)
|
||||
{
|
||||
if (AskYesNo (StringFormatter (LangString["LINUX_EMERGENCY_UNMOUNT_WARNING"], wstring (volume->Path)), false, true))
|
||||
{
|
||||
{
|
||||
BusyScope busy (this);
|
||||
volume = Core->EmergencyDismountVolume (volume);
|
||||
}
|
||||
emergencyCleanupPerformed = true;
|
||||
ShowWarning (StringFormatter (LangString["LINUX_EMERGENCY_UNMOUNTED"], wstring (volume->Path)));
|
||||
}
|
||||
else
|
||||
throw UserAbort (SRC_POS);
|
||||
}
|
||||
else
|
||||
throw;
|
||||
}
|
||||
#endif
|
||||
catch (DismountServiceCleanupFailed &e)
|
||||
{
|
||||
// The auxiliary mount is gone, so another attempt cannot reach the service.
|
||||
unconfirmedCleanups.push_back (e);
|
||||
continue;
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
if (twoPassMode && firstPass)
|
||||
volumesLeft.push_back (volume);
|
||||
else
|
||||
throw;
|
||||
}
|
||||
|
||||
if (volume->HiddenVolumeProtectionTriggered)
|
||||
ShowWarning (StringFormatter (LangString["DAMAGE_TO_HIDDEN_VOLUME_PREVENTED"], wstring (volume->Path)));
|
||||
|
||||
if (Preferences.Verbose)
|
||||
{
|
||||
if (!emergencyCleanupPerformed)
|
||||
{
|
||||
if (!message.IsEmpty())
|
||||
message += L'\n';
|
||||
message += StringFormatter (LangString["LINUX_VOL_UNMOUNTED"], wstring (volume->Path));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (twoPassMode && firstPass)
|
||||
{
|
||||
volumes = volumesLeft;
|
||||
|
||||
if (volumesInUse && interactive)
|
||||
{
|
||||
if (AskYesNo (LangString["UNMOUNTALL_LOCK_FAILED"], true, true))
|
||||
ignoreOpenFiles = true;
|
||||
else
|
||||
throw UserAbort (SRC_POS);
|
||||
}
|
||||
else
|
||||
throw;
|
||||
}
|
||||
#endif
|
||||
catch (...)
|
||||
{
|
||||
if (twoPassMode && firstPass)
|
||||
volumesLeft.push_back (volume);
|
||||
else
|
||||
throw;
|
||||
}
|
||||
else
|
||||
break;
|
||||
|
||||
if (volume->HiddenVolumeProtectionTriggered)
|
||||
ShowWarning (StringFormatter (LangString["DAMAGE_TO_HIDDEN_VOLUME_PREVENTED"], wstring (volume->Path)));
|
||||
|
||||
if (Preferences.Verbose)
|
||||
{
|
||||
if (!emergencyCleanupPerformed)
|
||||
{
|
||||
if (!message.IsEmpty())
|
||||
message += L'\n';
|
||||
message += StringFormatter (LangString["LINUX_VOL_UNMOUNTED"], wstring (volume->Path));
|
||||
}
|
||||
}
|
||||
firstPass = false;
|
||||
}
|
||||
|
||||
if (twoPassMode && firstPass)
|
||||
{
|
||||
volumes = volumesLeft;
|
||||
if (Preferences.Verbose && !message.IsEmpty())
|
||||
ShowInfo (message);
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
if (unconfirmedCleanups.empty())
|
||||
throw;
|
||||
|
||||
if (volumesInUse && interactive)
|
||||
{
|
||||
if (AskYesNo (LangString["UNMOUNTALL_LOCK_FAILED"], true, true))
|
||||
ignoreOpenFiles = true;
|
||||
else
|
||||
throw UserAbort (SRC_POS);
|
||||
}
|
||||
}
|
||||
else
|
||||
break;
|
||||
|
||||
firstPass = false;
|
||||
wxString otherFailure;
|
||||
try { throw; }
|
||||
catch (UserAbort &) { }
|
||||
catch (exception &e) { otherFailure = ExceptionToMessage (e); }
|
||||
catch (...) { otherFailure = ExceptionToMessage (UnknownException (SRC_POS)); }
|
||||
ThrowUnconfirmedCleanups (unconfirmedCleanups, otherFailure.ToStdWstring());
|
||||
}
|
||||
|
||||
if (Preferences.Verbose && !message.IsEmpty())
|
||||
ShowInfo (message);
|
||||
if (!unconfirmedCleanups.empty())
|
||||
ThrowUnconfirmedCleanups (unconfirmedCleanups, wstring());
|
||||
}
|
||||
|
||||
void UserInterface::DisplayVolumeProperties (const VolumeInfoList &volumes) const
|
||||
@@ -562,6 +603,11 @@ namespace VeraCrypt
|
||||
EX2MSG (MountPointUnavailable, LangString["LINUX_EX2MSG_MOUNTPOINTUNAVAILABLE"]);
|
||||
EX2MSG (MountServiceIncompatible, LangString["MOUNT_SERVICE_INCOMPATIBLE"]);
|
||||
EX2MSG (MountServiceCleanupFailed, LangString["MOUNT_SERVICE_CLEANUP_FAILED"]);
|
||||
EX2MSG (DismountServiceCleanupFailed, LangString["DISMOUNT_SERVICE_CLEANUP_FAILED"]);
|
||||
EX2MSG (MountServiceUnavailable, LangString["MOUNT_SERVICE_UNAVAILABLE"]);
|
||||
EX2MSG (VolumeDiscoveryFailed, LangString["VOLUME_DISCOVERY_FAILED"]);
|
||||
EX2MSG (MountedVolumeInUse, LangString["VOLUME_IN_USE"]);
|
||||
EX2MSG (TimeOut, LangString["OPERATION_TIMED_OUT"]);
|
||||
EX2MSG (NoDriveLetterAvailable, LangString["NO_FREE_DRIVES"]);
|
||||
EX2MSG (PasswordEmpty, LangString["LINUX_EX2MSG_PASSWORDEMPTY"]);
|
||||
EX2MSG (PasswordIncorrect, LangString["PASSWORD_WRONG"]);
|
||||
@@ -1305,6 +1351,7 @@ const FileManager fileManagers[] = {
|
||||
, cmdLine.ArgEmergencyUnmount
|
||||
#endif
|
||||
);
|
||||
if (!cmdLine.ArgUnresolvedMounts.empty()) throw VolumeDiscoveryFailed (SRC_POS, wstring (cmdLine.ArgUnresolvedMounts.front()));
|
||||
return true;
|
||||
|
||||
case CommandId::DisplayVersion:
|
||||
@@ -1312,7 +1359,9 @@ const FileManager fileManagers[] = {
|
||||
return true;
|
||||
|
||||
case CommandId::DisplayVolumeProperties:
|
||||
if (cmdLine.ArgVolumes.empty() && !cmdLine.ArgUnresolvedMounts.empty()) throw VolumeDiscoveryFailed (SRC_POS, wstring (cmdLine.ArgUnresolvedMounts.front()));
|
||||
DisplayVolumeProperties (cmdLine.ArgVolumes);
|
||||
if (!cmdLine.ArgUnresolvedMounts.empty()) throw VolumeDiscoveryFailed (SRC_POS, wstring (cmdLine.ArgUnresolvedMounts.front()));
|
||||
return true;
|
||||
|
||||
case CommandId::Help:
|
||||
@@ -1675,10 +1724,12 @@ const FileManager fileManagers[] = {
|
||||
return true;
|
||||
|
||||
case CommandId::ListVolumes:
|
||||
if (cmdLine.ArgVolumes.empty() && !cmdLine.ArgUnresolvedMounts.empty()) throw VolumeDiscoveryFailed (SRC_POS, wstring (cmdLine.ArgUnresolvedMounts.front()));
|
||||
if (Preferences.Verbose)
|
||||
DisplayVolumeProperties (cmdLine.ArgVolumes);
|
||||
else
|
||||
ListMountedVolumes (cmdLine.ArgVolumes);
|
||||
if (!cmdLine.ArgUnresolvedMounts.empty()) throw VolumeDiscoveryFailed (SRC_POS, wstring (cmdLine.ArgUnresolvedMounts.front()));
|
||||
return true;
|
||||
|
||||
case CommandId::RestoreHeaders:
|
||||
@@ -1914,6 +1965,9 @@ const FileManager fileManagers[] = {
|
||||
VC_CONVERT_EXCEPTION (MountPointUnavailable);
|
||||
VC_CONVERT_EXCEPTION (MountServiceIncompatible);
|
||||
VC_CONVERT_EXCEPTION (MountServiceCleanupFailed);
|
||||
VC_CONVERT_EXCEPTION (DismountServiceCleanupFailed);
|
||||
VC_CONVERT_EXCEPTION (MountServiceUnavailable);
|
||||
VC_CONVERT_EXCEPTION (VolumeDiscoveryFailed);
|
||||
VC_CONVERT_EXCEPTION (NoDriveLetterAvailable);
|
||||
VC_CONVERT_EXCEPTION (TemporaryDirectoryFailure);
|
||||
VC_CONVERT_EXCEPTION (UnsupportedSectorSizeHiddenVolumeProtection);
|
||||
|
||||
@@ -61,6 +61,7 @@ namespace VeraCrypt
|
||||
virtual void ListEMVTokenKeyfiles () const = 0;
|
||||
virtual shared_ptr <VolumeInfo> MountVolume (MountOptions &options, bool tryCachedPasswords = true) const;
|
||||
virtual shared_ptr <VolumeInfo> MountVolumeThread (MountOptions &options) const { return Core->MountVolume (options);}
|
||||
virtual shared_ptr <VolumeInfo> DismountVolumeThread (shared_ptr <VolumeInfo> volume, bool ignoreOpenFiles, bool interactive = true) const { return Core->DismountVolume (volume, ignoreOpenFiles); }
|
||||
virtual VolumeInfoList MountAllDeviceHostedVolumes (MountOptions &options) const;
|
||||
virtual VolumeInfoList MountAllFavoriteVolumes (MountOptions &options);
|
||||
virtual void OpenExplorerWindow (const DirectoryPath &path);
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
Copyright (c) 2026 AM Crypto. All rights reserved.
|
||||
|
||||
Governed by the Apache License 2.0, included in License.txt.
|
||||
*/
|
||||
|
||||
// Local GUI discovery state. Kept independent of wxWidgets so lifecycle
|
||||
// decisions can be checked without a native event loop or mounted volumes.
|
||||
#ifndef TC_HEADER_Main_VolumeSnapshot
|
||||
#define TC_HEADER_Main_VolumeSnapshot
|
||||
|
||||
#include <chrono>
|
||||
|
||||
namespace VeraCrypt
|
||||
{
|
||||
class VolumeSnapshotState
|
||||
{
|
||||
public:
|
||||
using Clock = std::chrono::steady_clock;
|
||||
VolumeSnapshotState () : Available (false), Current (false), Complete (false) { }
|
||||
|
||||
// Staleness only suspends decisions. Activity counters are cumulative per
|
||||
// volume instance, so observation gaps do not invalidate idle tracking.
|
||||
void RecordSample (Clock::time_point sampledAt, bool complete)
|
||||
{
|
||||
Available = Current = true;
|
||||
Complete = complete;
|
||||
SampledAt = sampledAt;
|
||||
}
|
||||
void Invalidate () { Current = false; }
|
||||
bool HasSample () const { return Available; }
|
||||
bool IsComplete () const { return Current && Complete; }
|
||||
bool IsFresh (Clock::time_point now = Clock::now()) const
|
||||
{
|
||||
return Current && Available && now - SampledAt < std::chrono::seconds (6);
|
||||
}
|
||||
bool CanConfirmEmpty (bool empty, Clock::time_point now = Clock::now()) const
|
||||
{
|
||||
return empty && IsComplete() && IsFresh (now);
|
||||
}
|
||||
|
||||
private:
|
||||
bool Available, Current, Complete;
|
||||
Clock::time_point SampledAt;
|
||||
};
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -192,10 +192,27 @@ namespace VeraCrypt
|
||||
if (sysEx)
|
||||
return ToWide (sysEx->what()) + L": " + sysEx->SystemText() + L": " + sysEx->GetSubject();
|
||||
|
||||
wstring message;
|
||||
if (ex.what() && !string (ex.what()).empty())
|
||||
return ToWide (GetTypeName (typeid (ex)) + ": " + ex.what());
|
||||
message = ToWide (GetTypeName (typeid (ex)) + ": " + ex.what());
|
||||
else
|
||||
message = ToWide (GetTypeName (typeid (ex)));
|
||||
|
||||
return ToWide (GetTypeName (typeid (ex)));
|
||||
// Wrapped and logged errors must keep the details attached by the thrower.
|
||||
const ExecutedProcessFailed *processEx = dynamic_cast <const ExecutedProcessFailed *> (&ex);
|
||||
if (processEx)
|
||||
{
|
||||
message += L": " + ToWide (processEx->GetCommand(), true) + L" (" + ToWide (processEx->GetExitCode()) + L")";
|
||||
string errorOutput = Trim (processEx->GetErrorOutput());
|
||||
if (!errorOutput.empty())
|
||||
message += L": " + ToWide (errorOutput, true);
|
||||
}
|
||||
|
||||
const Exception *vcEx = dynamic_cast <const Exception *> (&ex);
|
||||
if (vcEx && !vcEx->GetSubject().empty())
|
||||
message += L": " + vcEx->GetSubject();
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
string StringConverter::ToLower (const string &str)
|
||||
|
||||
@@ -17,17 +17,193 @@
|
||||
#include <sys/wait.h>
|
||||
#include "Process.h"
|
||||
#include "Platform/Exception.h"
|
||||
#include "Platform/Finally.h"
|
||||
#include "Platform/FileStream.h"
|
||||
#include "Platform/ForEach.h"
|
||||
#include "Platform/MemoryStream.h"
|
||||
#include "Platform/Mutex.h"
|
||||
#include "Platform/SystemException.h"
|
||||
#include "Platform/StringConverter.h"
|
||||
#include "Platform/Unix/Pipe.h"
|
||||
#include "Platform/Unix/Poller.h"
|
||||
#ifdef TC_MACOSX
|
||||
#include <chrono>
|
||||
#include <poll.h>
|
||||
#include <signal.h>
|
||||
#include <spawn.h>
|
||||
#include <crt_externs.h>
|
||||
#include <libproc.h>
|
||||
#endif
|
||||
|
||||
namespace VeraCrypt
|
||||
{
|
||||
|
||||
#ifdef TC_MACOSX
|
||||
uint64 Process::GetProcessStartTime (pid_t processId)
|
||||
{
|
||||
struct proc_bsdinfo info;
|
||||
if (proc_pidinfo (processId, PROC_PIDTBSDINFO, 0, &info, sizeof (info)) != sizeof (info))
|
||||
return 0;
|
||||
return info.pbi_start_tvsec * 1000000ULL + info.pbi_start_tvusec;
|
||||
}
|
||||
|
||||
bool Process::IsProcessRunning (pid_t processId, uint64 expectedStartTime)
|
||||
{
|
||||
if (processId <= 1) throw ParameterIncorrect (SRC_POS);
|
||||
if (kill (processId, 0) == -1 && errno == ESRCH) return false;
|
||||
uint64 startTime = expectedStartTime ? GetProcessStartTime (processId) : 0;
|
||||
// An inaccessible process remains pending. Only absence or a positively
|
||||
// identified replacement proves that the captured instance has exited.
|
||||
return !expectedStartTime || !startTime || startTime == expectedStartTime;
|
||||
}
|
||||
|
||||
// Bounded children that survived SIGKILL, such as a child in uninterruptible
|
||||
// sleep. Later calls reap them and start no new child until then, so repeated
|
||||
// timeouts cannot accumulate stuck children or zombies. Never destroyed: a
|
||||
// detached discovery worker may still run during static destruction.
|
||||
static Mutex &GetAbandonedChildrenMutex ()
|
||||
{
|
||||
static Mutex *mutex = new Mutex;
|
||||
return *mutex;
|
||||
}
|
||||
|
||||
static vector <pid_t> &GetAbandonedChildren ()
|
||||
{
|
||||
static vector <pid_t> *children = new vector <pid_t>;
|
||||
return *children;
|
||||
}
|
||||
|
||||
string Process::ExecuteBounded (const string &processName, const list <string> &arguments, int timeOut, size_t outputLimit)
|
||||
{
|
||||
if (processName.empty() || processName[0] != '/' || timeOut <= 0 || outputLimit == 0)
|
||||
throw ParameterIncorrect (SRC_POS);
|
||||
|
||||
{
|
||||
ScopeLock lock (GetAbandonedChildrenMutex());
|
||||
vector <pid_t> &children = GetAbandonedChildren();
|
||||
for (size_t i = 0; i < children.size(); )
|
||||
{
|
||||
pid_t waited = waitpid (children[i], NULL, WNOHANG);
|
||||
if (waited == 0 || (waited == -1 && errno == EINTR))
|
||||
++i;
|
||||
else
|
||||
children.erase (children.begin() + i);
|
||||
}
|
||||
if (!children.empty())
|
||||
throw TimeOut (SRC_POS, StringConverter::ToWide (processName));
|
||||
}
|
||||
|
||||
const auto deadline = chrono::steady_clock::now() + chrono::milliseconds (timeOut);
|
||||
int descriptors[4] = { -1, -1, -1, -1 };
|
||||
finally_do_arg (int *, descriptors, { for (int i = 0; i < 4; ++i) if (finally_arg[i] != -1) close (finally_arg[i]); });
|
||||
throw_sys_if (pipe (descriptors) != 0);
|
||||
throw_sys_if (pipe (descriptors + 2) != 0);
|
||||
for (int i = 0; i < 4; ++i)
|
||||
throw_sys_if (fcntl (descriptors[i], F_SETFD, FD_CLOEXEC) == -1);
|
||||
for (int i = 0; i < 4; i += 2)
|
||||
throw_sys_if (fcntl (descriptors[i], F_SETFL, O_NONBLOCK) == -1);
|
||||
|
||||
posix_spawn_file_actions_t actions;
|
||||
int error = posix_spawn_file_actions_init (&actions);
|
||||
if (error) throw SystemException (SRC_POS, error);
|
||||
finally_do_arg (posix_spawn_file_actions_t *, &actions, { posix_spawn_file_actions_destroy (finally_arg); });
|
||||
posix_spawnattr_t attributes;
|
||||
error = posix_spawnattr_init (&attributes);
|
||||
if (error) throw SystemException (SRC_POS, error);
|
||||
finally_do_arg (posix_spawnattr_t *, &attributes, { posix_spawnattr_destroy (finally_arg); });
|
||||
// Avoid fork-side library calls and leaking service/key-bearing descriptors
|
||||
// when discovery runs on the GUI's worker thread.
|
||||
if ((error = posix_spawnattr_setflags (&attributes, POSIX_SPAWN_CLOEXEC_DEFAULT))
|
||||
|| (error = posix_spawn_file_actions_addopen (&actions, STDIN_FILENO, "/dev/null", O_RDONLY, 0))
|
||||
|| (error = posix_spawn_file_actions_adddup2 (&actions, descriptors[1], STDOUT_FILENO))
|
||||
|| (error = posix_spawn_file_actions_adddup2 (&actions, descriptors[3], STDERR_FILENO)))
|
||||
throw SystemException (SRC_POS, error);
|
||||
|
||||
vector <char *> args;
|
||||
args.push_back (const_cast <char *> (processName.c_str()));
|
||||
for (const string &argument : arguments)
|
||||
args.push_back (const_cast <char *> (argument.c_str()));
|
||||
args.push_back (nullptr);
|
||||
pid_t child;
|
||||
error = posix_spawn (&child, processName.c_str(), &actions, &attributes, &args[0], *_NSGetEnviron());
|
||||
if (error) throw SystemException (SRC_POS, error);
|
||||
finally_do_arg (pid_t *, &child, {
|
||||
if (*finally_arg > 0)
|
||||
{
|
||||
// This is our unreaped child, never a PID recovered from metadata.
|
||||
// A child in uninterruptible sleep cannot be reaped within the
|
||||
// deadline; leave it to a later call rather than blocking this one.
|
||||
kill (*finally_arg, SIGKILL);
|
||||
bool finished = false;
|
||||
for (int attempt = 0; attempt < 100 && !finished; ++attempt)
|
||||
{
|
||||
pid_t waited = waitpid (*finally_arg, NULL, WNOHANG);
|
||||
finished = waited == *finally_arg || (waited == -1 && errno != EINTR);
|
||||
if (!finished)
|
||||
poll (nullptr, 0, 10);
|
||||
}
|
||||
if (!finished)
|
||||
{
|
||||
ScopeLock lock (GetAbandonedChildrenMutex());
|
||||
GetAbandonedChildren().push_back (*finally_arg);
|
||||
}
|
||||
}
|
||||
});
|
||||
close (descriptors[1]); descriptors[1] = -1;
|
||||
close (descriptors[3]); descriptors[3] = -1;
|
||||
struct pollfd fds[2] = { { descriptors[0], POLLIN, 0 }, { descriptors[2], POLLIN, 0 } };
|
||||
string output[2];
|
||||
int status = 0;
|
||||
int exitPoll = 1;
|
||||
while (child > 0 || fds[0].fd != -1 || fds[1].fd != -1)
|
||||
{
|
||||
if (child > 0)
|
||||
{
|
||||
pid_t waited = waitpid (child, &status, WNOHANG);
|
||||
if (waited == child) child = -1;
|
||||
else if (waited == -1 && errno != EINTR)
|
||||
{
|
||||
if (errno == ECHILD) child = -1;
|
||||
throw SystemException (SRC_POS);
|
||||
}
|
||||
}
|
||||
if (child == -1 && fds[0].fd == -1 && fds[1].fd == -1)
|
||||
break;
|
||||
auto remaining = chrono::duration_cast <chrono::milliseconds> (deadline - chrono::steady_clock::now()).count();
|
||||
if (remaining <= 0) throw TimeOut (SRC_POS, StringConverter::ToWide (processName));
|
||||
int pollTimeout = static_cast <int> (remaining < 50 ? remaining : 50);
|
||||
if (fds[0].fd == -1 && fds[1].fd == -1)
|
||||
{
|
||||
// Output is complete and the exit status normally follows at once.
|
||||
// Do not sleep a whole output-poll interval before reaping it.
|
||||
if (exitPoll < pollTimeout) pollTimeout = exitPoll;
|
||||
exitPoll = exitPoll < 25 ? exitPoll * 2 : 50;
|
||||
}
|
||||
int result = poll (fds, 2, pollTimeout);
|
||||
if (result == -1 && errno == EINTR) continue;
|
||||
throw_sys_if (result == -1);
|
||||
for (int i = 0; i < 2; ++i)
|
||||
{
|
||||
if (fds[i].fd == -1 || !fds[i].revents) continue;
|
||||
char buffer[8192];
|
||||
ssize_t count = read (fds[i].fd, buffer, sizeof (buffer));
|
||||
if (count > 0)
|
||||
{
|
||||
if (static_cast <size_t> (count) > outputLimit - output[0].size() - output[1].size())
|
||||
throw ParameterTooLarge (SRC_POS);
|
||||
output[i].append (buffer, count);
|
||||
}
|
||||
else if (count == 0) fds[i].fd = -1;
|
||||
else if (errno != EINTR && errno != EAGAIN) throw SystemException (SRC_POS);
|
||||
}
|
||||
}
|
||||
int exitCode = WIFEXITED (status) ? WEXITSTATUS (status) : 1;
|
||||
if (exitCode != 0)
|
||||
throw ExecutedProcessFailed (SRC_POS, processName, exitCode, output[1]);
|
||||
return output[0];
|
||||
}
|
||||
#endif
|
||||
|
||||
bool Process::IsExecutable(const std::string& path) {
|
||||
struct stat sb;
|
||||
if (stat(path.c_str(), &sb) == 0) {
|
||||
|
||||
@@ -34,6 +34,12 @@ namespace VeraCrypt
|
||||
static bool IsExecutable(const std::string& path);
|
||||
static std::string FindSystemBinary(const char* name, std::string& errorMsg);
|
||||
static string Execute (const string &processName, const list <string> &arguments, int timeOut = -1, ProcessExecFunctor *execFunctor = nullptr, const Buffer *inputData = nullptr);
|
||||
#ifdef TC_MACOSX
|
||||
static uint64 GetProcessStartTime (pid_t processId);
|
||||
static bool IsProcessRunning (pid_t processId, uint64 expectedStartTime = 0);
|
||||
// For read-only discovery only: a deadline aborts and reaps the child.
|
||||
static string ExecuteBounded (const string &processName, const list <string> &arguments, int timeOut, size_t outputLimit = 16 * 1024 * 1024);
|
||||
#endif
|
||||
#if defined(TC_LINUX)
|
||||
static bool IsRunningUnderAppImage (const string &executablePath);
|
||||
#endif
|
||||
|
||||
+19
-2
@@ -23,15 +23,32 @@ namespace VeraCrypt
|
||||
class VolumeInfo;
|
||||
typedef list < shared_ptr <VolumeInfo> > VolumeInfoList;
|
||||
|
||||
// Unreadable candidates are not VolumeInfo objects: their slot and identity
|
||||
// are unknown. Callers may act on verified volumes without claiming that an
|
||||
// incomplete inventory proves absence (or that every volume was unmounted).
|
||||
struct VolumeDiscoveryResult
|
||||
{
|
||||
VolumeInfoList Volumes;
|
||||
list <DirectoryPath> UnresolvedMounts;
|
||||
bool IsComplete () const { return UnresolvedMounts.empty(); }
|
||||
};
|
||||
|
||||
class VolumeInfo : public Serializable
|
||||
{
|
||||
public:
|
||||
VolumeInfo () { }
|
||||
VolumeInfo () : Discovery (DiscoveryUnknown) { }
|
||||
virtual ~VolumeInfo () { }
|
||||
|
||||
TC_SERIALIZABLE (VolumeInfo);
|
||||
static bool FirstVolumeMountedAfterSecond (shared_ptr <VolumeInfo> first, shared_ptr <VolumeInfo> second);
|
||||
void Set (const Volume &volume);
|
||||
shared_ptr <VolumeInfo> Clone () const { return shared_ptr <VolumeInfo> (new VolumeInfo (*this)); }
|
||||
|
||||
// Local discovery hints only. Never serialized into the legacy control
|
||||
// file or used as authority for a destructive operation. A GUI-retained
|
||||
// entry whose control metadata is now unreadable has no current counters.
|
||||
enum DiscoveryState { DiscoveryUnknown, ImageAttached, ImageAbsent, ControlUnavailable };
|
||||
DiscoveryState Discovery;
|
||||
|
||||
// Modifying this structure can introduce incompatibility with previous versions
|
||||
DirectoryPath AuxMountPoint;
|
||||
@@ -63,7 +80,7 @@ namespace VeraCrypt
|
||||
int Pim;
|
||||
bool MasterKeyVulnerable;
|
||||
private:
|
||||
VolumeInfo (const VolumeInfo &);
|
||||
VolumeInfo (const VolumeInfo &) = default;
|
||||
VolumeInfo &operator= (const VolumeInfo &);
|
||||
};
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user