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:
Mounir IDRASSI
2026-09-28 03:17:28 +02:00
parent aedb2ef863
commit 596beb82a1
38 changed files with 2551 additions and 311 deletions
+69
View File
@@ -0,0 +1,69 @@
# macOS lifecycle regression checks
Run these checks on macOS with Xcode Command Line Tools and Python 3. They do not
require administrator privileges, mounted containers, or an installed test app.
Build the matching VeraCrypt sources first. Use a clean build after changing
headers: the current makefiles do not track every header dependency. The archive
architecture must match the compiler's default architecture.
From the repository root, set `VC_TEST_BUILD_SRC` to the `src` directory of that
build, then run:
```sh
VC_TEST_BUILD_SRC=/absolute/path/to/build/src
python3 Tests/test_macos_discovery.py --platform-archive "$VC_TEST_BUILD_SRC/Platform/Platform.a"
python3 Tests/test_fuset_cleanup.py --build-dir "$VC_TEST_BUILD_SRC"
```
The discovery runner compiles the production plist and batch-refresh methods
with an in-memory inventory provider. It checks exact and legacy alias matches,
unresolved inventory, stale-field invalidation, one query per refresh, and fresh
discovery before destructive operations. It also runs `macos_process_test.cpp`
against the real platform archive, checking subprocess deadlines, output limits,
descriptor isolation, error reporting, and child reaping with its own helper
processes. `macos_volume_state_test.cpp` includes production headers directly to
check auxiliary mount owner/backend/basename filtering and initial, partial,
invalidated, and stale snapshot decisions.
The cleanup runner compiles production cleanup and rollback methods with mocked
mount, service, and device operations. It checks failure ordering, reporting of
unconfirmed service exits after auxiliary-mount removal, retryable busy
unmounts, per-volume hidden-protection refresh, and responsive probes during
busy startup rollback. It also runs the production multi-volume unmount loop
with scripted outcomes: every unconfirmed service exit must be reported, even
when another volume fails or a forced-unmount prompt is declined. Finally, it
runs `macos_cleanup_state_test.cpp` against the real serialization code to
check that cleanup failure details survive IPC and that local display state
leaves the legacy `/control` bytes unchanged.
These tests exercise state and serialization contracts. They do not establish
real backend timing, GUI rendering, or filesystem behavior under forced unmount.
For an ordinary integration check with a FUSE-T GUI build, close other VeraCrypt
processes and dismount their volumes first. In a logged-in macOS desktop session:
```sh
python3 Tests/test_macos_gui_lifecycle.py --binary "$VC_TEST_BUILD_SRC/Main/VeraCrypt"
python3 Tests/test_macos_gui_inactivity.py --binary "$VC_TEST_BUILD_SRC/Main/VeraCrypt"
python3 Tests/test_macos_gui_teardown.py --binary "$VC_TEST_BUILD_SRC/Main/VeraCrypt"
```
These use isolated preferences and disposable file containers. The lifecycle
check verifies write/fsync/remount integrity, background startup with a mounted
volume, refresh after a CLI dismount, and automatic GUI exit. It checks service
exit, closed backing-file handles, and removal of the auxiliary mount and
shutdown endpoint. The inactivity check takes about two minutes: it verifies
that automatically unmounting one idle volume does not restart another volume's
idle timer. The teardown check needs an unsigned local build and clang, and
takes about three minutes. It slows a service down with `fuset_startup_faults.c`
and verifies two automatic-unmount cases: a normal quit request that arrives
meanwhile is honored, including unmount on quit; and when service exit cannot be
confirmed, a warning keeps the background application from exiting silently.
That warning stays on screen until the test ends. Failed-run artifacts are
retained for diagnosis; use `--keep-artifacts` to retain successful runs as well.
Use disposable containers for ordinary create/write/fsync/unmount/remount checks,
released-client compatibility, and user/root ownership combinations. Keep logs
private and verify service exit, closed backing-file handles, removed auxiliary
mounts and endpoints, and payload integrity after remounting.
+26 -1
View File
@@ -1,4 +1,5 @@
/* Scoped macOS fault injection for test_fuset_dismount.py --startup-faults.
/* Scoped macOS fault injection for test_fuset_dismount.py --startup-faults
* and test_macos_gui_teardown.py (delayed service teardown).
* Copyright (c) 2026 AM Crypto. Licensed under the Apache License 2.0.
*/
#include <errno.h>
@@ -92,6 +93,12 @@ static int test_stat (const char *path, struct stat *value)
return stat (path, value);
}
static unsigned fault_delay (void)
{
const char *delay = getenv ("VC_FUSET_TEST_DELAY");
return delay ? (unsigned) atoi (delay) : 10;
}
static int test_unmount (const char *path, int flags)
{
const char *gate = getenv ("VC_FUSET_TEST_UNMOUNT_GATE");
@@ -101,9 +108,26 @@ static int test_unmount (const char *path, int flags)
errno = EBUSY;
return -1;
}
if (mode_is ("unmount-delay") && fixture_path (path, ""))
{
/* The service removes SMB slowly; its caller waits for the reply. */
mark_fault();
sleep (fault_delay());
}
return unmount (path, flags);
}
static int test_unlinkat (int fd, const char *path, int flags)
{
if (mode_is ("cleanup-delay") && (flags & AT_REMOVEDIR) && strstr (path, ".veracrypt_aux_mnt"))
{
/* The service outlives its caller's exit wait after SMB removal. */
mark_fault();
sleep (fault_delay());
}
return unlinkat (fd, path, flags);
}
#define INTERPOSE(replacement, original) \
__attribute__((used)) static const struct { const void *replace; const void *replacee; } \
interpose_##original __attribute__((section("__DATA,__interpose"))) = { \
@@ -113,3 +137,4 @@ INTERPOSE (test_connect, connect);
INTERPOSE (test_open, open);
INTERPOSE (test_stat, stat);
INTERPOSE (test_unmount, unmount);
INTERPOSE (test_unlinkat, unlinkat);
+66
View File
@@ -0,0 +1,66 @@
// Exercise cleanup-failure IPC and preserve the released /control wire format.
#include "Volume/VolumeInfo.h"
#include "Core/CoreException.h"
#include "Platform/MemoryStream.h"
#include "Platform/StringConverter.h"
#include <cstring>
#include <iostream>
#include <unistd.h>
using namespace VeraCrypt;
static void Require (bool condition, const char *message)
{
if (!condition) throw std::runtime_error (message);
}
int main ()
{
try
{
shared_ptr <VolumeInfo> volume (new VolumeInfo);
volume->EncryptionAlgorithmBlockSize = volume->EncryptionAlgorithmKeySize = volume->EncryptionAlgorithmMinBlockSize = 0;
volume->HeaderCreationTime = volume->VolumeCreationTime = 0;
volume->HiddenVolumeProtectionTriggered = volume->SystemEncryption = volume->MasterKeyVulnerable = false;
volume->MinRequiredProgramVersion = volume->Pkcs5IterationCount = volume->ProgramVersion = 0;
volume->Protection = VolumeProtection::None;
volume->SerialInstanceNumber = 123456789;
volume->Size = volume->TopWriteOffset = volume->TotalDataRead = volume->TotalDataWritten = 0;
volume->SlotNumber = 7;
volume->Type = VolumeType::Normal;
volume->Pim = 0;
volume->AuxMountPoint = "/private/tmp/unit-aux";
volume->Path = VolumePath (wstring (L"/private/tmp/unit-container"));
volume->VirtualDevice = "/dev/disk42";
shared_ptr <MemoryStream> controlBefore (new MemoryStream), controlAfter (new MemoryStream);
volume->Serialize (controlBefore);
volume->Discovery = VolumeInfo::ControlUnavailable;
volume->Serialize (controlAfter);
ConstBufferPtr before = *controlBefore, after = *controlAfter;
Require (before.Size() == after.Size() && memcmp (before.Get(), after.Get(), before.Size()) == 0, "local status changed the legacy control format");
shared_ptr <Stream> control (new MemoryStream (before));
Require (Serializable::DeserializeNew <VolumeInfo> (control)->Discovery == VolumeInfo::DiscoveryUnknown, "local hint unexpectedly serialized");
shared_ptr <VolumeInfo> clone = volume->Clone();
clone->VirtualDevice = DevicePath();
clone->Discovery = VolumeInfo::ImageAbsent;
Require (!volume->VirtualDevice.IsEmpty() && volume->Discovery == VolumeInfo::ControlUnavailable, "clone shared mutable fields");
// A core helper reports an unconfirmed service exit through the regular exception serializer.
DismountServiceCleanupFailed failure ("unit", L"pid=1234, auxiliary mount=/private/tmp/unit-aux");
shared_ptr <Stream> stream (new MemoryStream);
failure.Serialize (stream);
shared_ptr <DismountServiceCleanupFailed> restored = Serializable::DeserializeNew <DismountServiceCleanupFailed> (stream);
Require (restored->GetSubject() == failure.GetSubject() && string (restored->what()) == "unit", "lost cleanup failure details");
// Wrappers and background logs format errors with ToExceptionString.
Require (StringConverter::ToExceptionString (*restored).find (failure.GetSubject()) != wstring::npos, "formatting dropped cleanup failure details");
ExecutedProcessFailed inventory ("unit", "/usr/bin/hdiutil", 7, "inventory-error-detail\n");
wstring formatted = StringConverter::ToExceptionString (inventory);
Require (formatted.find (L"/usr/bin/hdiutil (7): inventory-error-detail") != wstring::npos, "formatting dropped subprocess failure details");
std::cout << "PASS: cleanup failure IPC and formatting, subprocess failure formatting, snapshot independence, unchanged control format\n";
}
catch (std::exception &e) { std::cerr << e.what() << '\n'; return 1; }
return 0;
}
+89
View File
@@ -0,0 +1,89 @@
// Read-only subprocess tests. Every child is this test executable; no mounts,
// privilege changes, or installed VeraCrypt services are involved.
#include "Platform/Platform.h"
#include "Platform/Unix/Process.h"
#include <chrono>
#include <fcntl.h>
#include <iostream>
#include <signal.h>
#include <sys/wait.h>
#include <unistd.h>
using namespace VeraCrypt;
static void Require (bool condition, const char *message)
{
if (!condition) throw std::runtime_error (message);
}
static int DescriptorCount ()
{
int count = 0;
for (int fd = 0; fd < 256; ++fd)
if (fcntl (fd, F_GETFD) != -1) ++count;
return count;
}
int main (int argc, char **argv)
{
if (argc > 1)
{
std::string mode = argv[1];
if (mode == "success")
{
char byte;
if (read (STDIN_FILENO, &byte, 1) != 0 || fcntl (80, F_GETFD) != -1) return 9;
write (STDOUT_FILENO, "complete", 8);
return 0;
}
if (mode == "failure") { write (STDERR_FILENO, "expected", 8); return 7; }
if (mode == "closed") { close (STDOUT_FILENO); close (STDERR_FILENO); sleep (5); return 0; }
if (mode == "stream")
{
for (;;) { write (STDOUT_FILENO, ".", 1); usleep (100); }
}
if (mode == "large")
{
char data[8192] = {};
for (;;) write (STDOUT_FILENO, data, sizeof (data));
}
sleep (5);
return 0;
}
try
{
uint64 startTime = Process::GetProcessStartTime (getpid());
Require (startTime != 0 && Process::IsProcessRunning (getpid(), startTime), "own process instance not recognized");
Require (!Process::IsProcessRunning (getpid(), startTime + 1), "different process instance accepted");
Require (Process::IsProcessRunning (getpid()), "unknown birth time discarded a live process");
int nullFd = open ("/dev/null", O_RDONLY);
Require (nullFd >= 0 && dup2 (nullFd, 80) == 80, "test descriptor setup");
close (nullFd);
int before = DescriptorCount();
std::cout << "process: success" << std::endl;
Require (Process::ExecuteBounded (argv[0], { "success" }, 1000) == "complete", "output/descriptor isolation");
std::cout << "process: failure" << std::endl;
try { Process::ExecuteBounded (argv[0], { "failure" }, 1000); throw std::runtime_error ("missing child error"); }
catch (ExecutedProcessFailed &e) { Require (e.GetExitCode() == 7 && e.GetErrorOutput() == "expected", "child error details"); }
for (const auto &mode : { "silent", "closed", "stream" })
{
std::cout << "process: " << mode << std::endl;
auto start = std::chrono::steady_clock::now();
try { Process::ExecuteBounded (argv[0], { mode }, 150); throw std::runtime_error ("missing timeout"); }
catch (TimeOut &) { }
Require (std::chrono::steady_clock::now() - start < std::chrono::seconds (2), "deadline overrun");
int status;
Require (waitpid (-1, &status, WNOHANG) == -1 && errno == ECHILD, "timed-out child not reaped");
}
std::cout << "process: output cap" << std::endl;
try { Process::ExecuteBounded (argv[0], { "large" }, 1000, 64); throw std::runtime_error ("missing output cap"); }
catch (ParameterTooLarge &) { }
int status;
Require (waitpid (-1, &status, WNOHANG) == -1 && errno == ECHILD, "output-limited child not reaped");
Require (DescriptorCount() == before, "descriptor leak");
close (80);
std::cout << "PASS: output, errors, descriptor isolation, silent/closed/stream deadlines, output cap, reaping\n";
}
catch (std::exception &e) { std::cerr << e.what() << '\n'; return 1; }
return 0;
}
+61
View File
@@ -0,0 +1,61 @@
// Check production discovery policy without creating mounts or native windows.
#include "Core/Unix/MountedFilesystem.h"
#include "Main/VolumeSnapshot.h"
#include <iostream>
using namespace VeraCrypt;
static void Require (bool condition, const char *message)
{
if (!condition) throw std::runtime_error (message);
}
int main ()
{
try
{
VolumeSnapshotState state;
using Clock = VolumeSnapshotState::Clock;
using std::chrono::seconds;
const Clock::time_point start = Clock::now();
Require (!state.HasSample() && !state.CanConfirmEmpty (true, start), "initial empty list was authoritative");
state.RecordSample (start, true);
Require (state.CanConfirmEmpty (true, start + seconds (1)), "fresh complete empty list ignored");
Require (!state.CanConfirmEmpty (false, start + seconds (1)), "nonempty list allowed auto-close");
Require (!state.IsFresh (start + seconds (8)) && !state.CanConfirmEmpty (true, start + seconds (8)), "stale empty list allowed auto-close");
state.RecordSample (start + seconds (8), true);
state.Invalidate();
Require (state.HasSample() && !state.IsFresh (start + seconds (9)) && !state.IsComplete(), "invalidated display sample remained authoritative");
state.RecordSample (start + seconds (10), false);
Require (state.IsFresh (start + seconds (11)) && !state.CanConfirmEmpty (true, start + seconds (11)), "partial inventory treated as complete absence");
state.RecordSample (start + seconds (12), true);
Require (state.HasSample() && !state.CanConfirmEmpty (true, start + seconds (18)), "slow result allowed auto-close");
MountedFilesystem mount;
const string prefix = ".veracrypt_aux_mnt";
mount.MountPoint = "/private/tmp/.veracrypt_aux_mnt-unit";
mount.Owner = 501;
for (const char *type : { "smbfs", "nfs", "macfuse", "osxfuse", "fusefs" })
{
mount.Type = type;
Require (mount.IsAuxiliaryMountCandidate (prefix, 501, 501), "supported auxiliary backend ignored");
}
mount.Type = "apfs";
Require (!mount.IsAuxiliaryMountCandidate (prefix, 501, 501), "unrelated filesystem entered discovery");
mount.Type = "smbfs";
mount.MountPoint = "/private/tmp/.veracrypt_aux_mnt-parent/ordinary";
Require (!mount.IsAuxiliaryMountCandidate (prefix, 501, 501), "parent path qualified as auxiliary mount");
mount.MountPoint = "/private/tmp/ordinary.veracrypt_aux_mnt";
Require (!mount.IsAuxiliaryMountCandidate (prefix, 501, 501), "substring qualified as auxiliary basename");
mount.MountPoint = "/private/tmp/.veracrypt_aux_mnt-unit";
mount.Owner = 502;
Require (!mount.IsAuxiliaryMountCandidate (prefix, 501, 502), "another user's mount entered discovery");
Require (mount.IsAuxiliaryMountCandidate (prefix, 0, 502), "elevated caller lost original user's mount");
Require (!mount.IsAuxiliaryMountCandidate (prefix, 0, 501), "root included unrelated user's mount");
mount.Owner = 0;
Require (mount.IsAuxiliaryMountCandidate (prefix, 501, 501), "root-owned auxiliary mount ignored");
std::cout << "PASS: startup/partial/stale snapshot policy, auxiliary basename/backend/owner scope\n";
}
catch (std::exception &e) { std::cerr << e.what() << '\n'; return 1; }
return 0;
}
+330
View File
@@ -0,0 +1,330 @@
#!/usr/bin/env python3
"""Test production cleanup state transitions with an in-memory FUSE service.
--build-dir is the src directory of a matching macOS build. All mount, process
and discovery operations in this harness are mocked; it never operates on a
real mount, service, or device.
"""
import argparse
from pathlib import Path
import subprocess
import tempfile
ROOT = Path(__file__).resolve().parents[1]
def check_rollback(work, build_dir):
source = (ROOT / "src/Driver/Fuse/FuseService.cpp").read_text()
worker = source[source.index("\tclass FuseServiceShutdownContext"):source.index("\n\t// Hold the original parent")]
worker = worker.replace("\tprivate:", "\tpublic:") # Test access to Serve; Start is never called.
prelude = r'''
#include "Platform/Platform.h"
#include "Platform/Unix/Pipe.h"
#include <chrono>
#include <cstring>
#include <fcntl.h>
#include <iostream>
#include <poll.h>
#include <sys/mount.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <unistd.h>
namespace VeraCrypt {
using FuseServiceClock=std::chrono::steady_clock;
static const uint64 VC_FUSE_SHUTDOWN_VERSION=3, VC_FUSE_SHUTDOWN_PROBE=0, VC_FUSE_SHUTDOWN_DISMOUNT=1, VC_FUSE_SHUTDOWN_FORCE=1;
static const char *VC_FUSE_SHUTDOWN_DIRECTORY_PREFIX="/unused-unit-path/";
static std::string FuseServiceShutdownDirectory;
static bool Mounted=true, Busy=true;
static int Attempts=0, Replies=0, Reply=-1, Polls=0, Finished=0;
static uint64 Command=VC_FUSE_SHUTDOWN_PROBE;
struct fuse {};
struct FuseService {
static uid_t GetUserId(){return getuid();} static gid_t GetGroupId(){return getgid();}
static uint64 GetSerialInstanceNumber(){return 42;} static unsigned GetSlotNumber(){return 7;}
};
struct SystemLog { static void WriteError(const std::string &){} static void WriteException(const std::exception &){} };
static void fuse_exit(fuse *){++Finished;}
static void fuse_service_unmount(fuse *){}
static bool fuse_service_find_mount(const char *,fsid_t &id){id.val[0]=101;id.val[1]=202;return Mounted;}
static bool fuse_service_same_mount(const fsid_t &a,const fsid_t &b){return a.val[0]==b.val[0] && a.val[1]==b.val[1];}
static sockaddr_un fuse_service_shutdown_address(const std::string &){return {};}
static void fuse_service_configure_socket(int){}
static bool fuse_service_socket_wait(int,short,int,int){return Polls++==0;}
static bool fuse_service_socket_transfer(int,void *data,size_t size,bool sending,int=-1,int=10000){
if(!sending){
if(size!=sizeof(uint64)*8)throw std::runtime_error("unexpected mock request");
uint64 frame[8]={3,Command,static_cast<uint64>(getpid()),42,7,0,101,202};
memcpy(data,frame,size);
} else if(size==sizeof(int32)){++Replies;Reply=*static_cast<int32 *>(data);}
return true;
}
static int FakeUnmount(const char *,int flags){
++Attempts;
if(flags!=MNT_FORCE)throw std::runtime_error("provisional rollback lost force mode");
if(Busy){errno=EBUSY;return -1;}Mounted=false;return 0;
}
static int FakePoll(struct pollfd *,nfds_t,int){return 1;}
static ssize_t FakeRecv(int,void *,size_t,int){return 0;}
static int FakeAccept(int,struct sockaddr *,socklen_t *){return open("/dev/null",O_RDWR);}
static int FakePeer(int,uid_t *uid,gid_t *gid){*uid=getuid();*gid=getgid();return 0;}
#define unmount FakeUnmount
#define poll FakePoll
#define recv FakeRecv
#define accept FakeAccept
#define getpeereid FakePeer
'''
tests = r'''
static void Require(bool value,const char *message){if(!value)throw std::runtime_error(message);}
int Run(){
for(uint64 command:{VC_FUSE_SHUTDOWN_PROBE,VC_FUSE_SHUTDOWN_DISMOUNT}){
Mounted=Busy=true;Attempts=Replies=Polls=Finished=0;Reply=-1;Command=command;
int startup=1000;
FuseServiceShutdownContext worker(NULL,"/in-memory-unit-mount",startup);
worker.StopPipe.reset(new Pipe);
worker.StartupReported=true;
worker.Serve();
Require(worker.StartupAborted && Mounted && Finished==0,"busy rollback stopped FUSE");
Require(Replies==1 && Reply==(command==VC_FUSE_SHUTDOWN_PROBE?0:EBUSY),"busy rollback starved endpoint");
Require(Attempts==(command==VC_FUSE_SHUTDOWN_PROBE?1:2),"rollback request retry storm");
Busy=false;worker.NextRollbackAttempt=FuseServiceClock::time_point();
worker.Serve();
Require(worker.Unmounted && !Mounted && Finished==1,"rollback did not resume after busy cleared");
}
std::cout<<"PASS: busy provisional rollback remains probeable, reports busy, and completes on retry\n";
return 0;
}
}
int main(){try{return VeraCrypt::Run();}catch(std::exception &e){std::cerr<<e.what()<<'\n';return 1;}}
'''
unit = work / "rollback.cpp"
unit.write_text(prelude + worker + tests)
command = ["clang++", "-std=c++11", "-DTC_UNIX", "-DTC_MACOSX", "-I" + str(ROOT / "src"), str(unit), str(build_dir.resolve() / "Platform/Platform.a"), "-Wl,-dead_strip", "-o", str(work / "rollback")]
subprocess.run(command, check=True)
subprocess.run([str(work / "rollback")], check=True, timeout=10)
def check_dismount_reporting(work, build_dir):
source = (ROOT / "src/Main/UserInterface.cpp").read_text()
end = source.index("\tvoid UserInterface::DisplayVolumeProperties")
start = source.index("\tvoid UserInterface::DismountVolumes")
helper = source.find("\tstatic void ThrowUnconfirmedCleanups")
method = source[helper if 0 <= helper < start else start:end]
prelude = r"""
#include "Volume/VolumeInfo.h"
#include "Volume/VolumeException.h"
#include "Core/CoreException.h"
#include "Platform/ForEach.h"
#include "Platform/StringConverter.h"
#include <deque>
#include <iostream>
#include <map>
namespace VeraCrypt {
struct wxString : std::wstring {
wxString () {}
wxString (const std::wstring &text) : std::wstring (text) {}
bool IsEmpty () const { return empty(); }
std::wstring ToStdWstring () const { return *this; }
wxString &operator+= (wchar_t c) { push_back (c); return *this; }
wxString &operator+= (const std::wstring &text) { append (text); return *this; }
};
struct StringFormatter {
StringFormatter (const std::wstring &format, const std::wstring &argument) : Text (format + L" " + argument) {}
operator std::wstring () const { return Text; }
std::wstring Text;
};
static struct { std::wstring operator[] (const char *key) const { return StringConverter::ToWide (std::string (key)); } } LangString;
enum Outcome { Unmounted, Busy, Unconfirmed, Failed };
static std::map <std::wstring, std::deque <Outcome> > Plan;
static bool ForceAnswer;
class UserInterface {
public:
struct BusyScope { BusyScope (const UserInterface *) {} };
void DismountVolumes (VolumeInfoList volumes, bool ignoreOpenFiles, bool interactive, bool emergencyCleanupRequested = false) const;
shared_ptr <VolumeInfo> DismountVolumeThread (shared_ptr <VolumeInfo> volume, bool, bool = true) const {
std::deque <Outcome> &steps = Plan[wstring (volume->Path)];
Outcome outcome = steps.empty() ? Unmounted : steps.front();
if (!steps.empty()) steps.pop_front();
if (outcome == Busy) throw MountedVolumeInUse (SRC_POS);
if (outcome == Unconfirmed) throw DismountServiceCleanupFailed (SRC_POS, L"service of " + wstring (volume->Path));
if (outcome == Failed) throw ParameterIncorrect (SRC_POS);
return volume;
}
bool AskYesNo (const std::wstring &, bool, bool) const { return ForceAnswer; }
void ShowWarning (const std::wstring &) const {}
void ShowInfo (const std::wstring &) const {}
static wxString ExceptionToMessage (const exception &e) { return StringConverter::ToExceptionString (e); }
struct { bool Verbose; } Preferences = { false };
};
"""
tests = r"""
static void Require (bool condition, const char *message) { if (!condition) throw std::runtime_error (message); }
static VolumeInfoList Volumes () {
VolumeInfoList volumes;
for (int i = 0; i < 2; ++i) {
shared_ptr <VolumeInfo> volume (new VolumeInfo);
volume->Path = VolumePath (wstring (i == 0 ? L"A" : L"B"));
volume->SerialInstanceNumber = i + 1;
volume->HiddenVolumeProtectionTriggered = false;
volumes.push_back (volume);
}
return volumes;
}
// Returns the details reported for unconfirmed cleanups, or the name of the other outcome.
static std::wstring Run (std::deque <Outcome> a, std::deque <Outcome> b, bool interactive, bool force = false) {
UserInterface ui; Plan.clear(); Plan[L"A"] = a; Plan[L"B"] = b; ForceAnswer = force;
try { ui.DismountVolumes (Volumes(), false, interactive); return L"<no error>"; }
catch (DismountServiceCleanupFailed &e) { return e.GetSubject(); }
catch (UserAbort &) { return L"<cancelled>"; }
catch (MountedVolumeInUse &) { return L"<busy>"; }
catch (ParameterIncorrect &) { return L"<failed>"; }
}
static bool Has (const std::wstring &text, const wchar_t *part) { return text.find (part) != std::wstring::npos; }
int Run () {
std::wstring r = Run ({Unconfirmed}, {Unmounted}, false);
Require (Has (r, L"service of A"), "unconfirmed cleanup lost when the other volume unmounts");
r = Run ({Unconfirmed}, {Busy, Busy}, false);
Require (Has (r, L"service of A") && Has (r, L"MountedVolumeInUse"), "unconfirmed cleanup lost when the other volume stays busy");
r = Run ({Unconfirmed}, {Failed, Failed}, false);
Require (Has (r, L"service of A") && Has (r, L"ParameterIncorrect"), "unconfirmed cleanup lost when the other volume fails");
r = Run ({Unconfirmed}, {Busy}, true, false);
Require (Has (r, L"service of A"), "unconfirmed cleanup lost when forced unmount is declined");
r = Run ({Unconfirmed}, {Unconfirmed}, false);
Require (Has (r, L"service of A") && Has (r, L"service of B"), "only one of two unconfirmed cleanups reported");
Require (Run ({Unmounted}, {Busy, Busy}, false) == L"<busy>", "busy volume error changed without unconfirmed cleanup");
Require (Run ({Unmounted}, {Busy}, true, false) == L"<cancelled>", "cancellation changed without unconfirmed cleanup");
Require (Run ({Unmounted}, {Busy, Unmounted}, true, true) == L"<no error>", "forced second pass failed");
std::cout << "PASS: multi-volume unmount reports every unconfirmed cleanup with other failures and cancellation\n";
return 0;
}
}
int main () { try { return VeraCrypt::Run(); } catch (std::exception &e) { std::cerr << e.what() << '\n'; return 1; } }
"""
unit = work / "dismount_reporting.cpp"
unit.write_text(prelude + method + tests)
command = ["clang++", "-std=c++11", "-DTC_UNIX", "-DTC_MACOSX"]
command += ["-I" + str(ROOT / p) for p in ("src", "src/Crypto", "src/Common", "src/Crypto/Argon2/include")]
command += [str(unit)] + [str(build_dir.resolve() / name) for name in ("Volume/Volume.a", "Platform/Platform.a")]
command += ["-Wl,-dead_strip", "-o", str(work / "dismount_reporting")]
subprocess.run(command, check=True)
subprocess.run([str(work / "dismount_reporting")], check=True, timeout=20)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--build-dir", required=True, type=Path)
args = parser.parse_args()
source = (ROOT / "src/Core/Unix/MacOSX/CoreMacOSX.cpp").read_text()
dismount = source[source.index("\tshared_ptr <VolumeInfo> CoreMacOSX::DismountVolume"):source.index("\tstatic void ClearDiskImageInfo")]
# Reuse the fully initialized public metadata fixture from the IPC test.
fixture = (ROOT / "Tests/macos_cleanup_state_test.cpp").read_text()
fixture = fixture[fixture.index("\t\tshared_ptr <VolumeInfo> volume"):fixture.index("\n\t\tshared_ptr <MemoryStream> controlBefore")]
prelude = r"""
#include "Volume/VolumeInfo.h"
#include "Core/CoreException.h"
#include "Platform/MemoryStream.h"
#include <iostream>
#include <unistd.h>
namespace VeraCrypt {
enum RequestMode { RequestOk, RequestBusy, RequestLostAfterUnmount };
static bool Mounted=true, FailWait=true, FailDiscovery=false, FailPreflight=false;
static RequestMode Request=RequestOk;
static int Preflights=0, Requests=0, Waits=0, Discoveries=0, Commands=0, CapturedReads=0;
static void FakeSync() {}
#define sync FakeSync
struct FuseService {
struct DismountRequest { pid_t ProcessId; uint64 ProcessStartTime, SerialInstanceNumber; unsigned SlotNumber; bool IgnoreOpenFiles, LegacyService; std::string SocketDirectory, AuxMountPoint; int32 MountId[2]; };
static DismountRequest PrepareDismount(const DirectoryPath &aux,uint64 serial,unsigned slot,bool force) {
++Preflights;
if(!Mounted || FailPreflight)throw MountServiceUnavailable("mock preflight");
DismountRequest request={}; request.ProcessId=1234; request.ProcessStartTime=987654321; request.SerialInstanceNumber=serial; request.SlotNumber=slot;
request.AuxMountPoint=aux; request.IgnoreOpenFiles=force; request.MountId[0]=101; request.MountId[1]=202; return request;
}
static bool IsDismountMountPresent(const DismountRequest &) { return Mounted; }
static pid_t RequestDismount(const DismountRequest &request) {
++Requests;
if(Request==RequestBusy)throw MountedVolumeInUse("mock busy");
Mounted=false;
if(Request==RequestLostAfterUnmount)throw MountServiceUnavailable("mock request", L"service reply lost");
return request.ProcessId;
}
static void WaitForDismount(pid_t pid,const DirectoryPath &,unsigned,int,uint64 startTime) {
++Waits; if(pid!=1234 || startTime!=987654321)throw std::runtime_error("wrong service identity");
if(FailWait)throw DismountServiceCleanupFailed("mock timeout", L"pid=1234, auxiliary mount=/in-memory");
}
static void DismountLegacy(const DismountRequest &) { throw std::runtime_error("unexpected legacy path"); }
};
struct Process {
static std::string Execute(const std::string &,const std::list<std::string> &) { ++Commands; throw std::runtime_error("unexpected disk command"); }
};
class CoreMacOSX {
public:
shared_ptr<VolumeInfo> DismountVolume(shared_ptr<VolumeInfo>, bool=false, bool=false);
void UpdateMountedVolumeInfo(shared_ptr<VolumeInfo> volume) {
++Discoveries; if(FailDiscovery)throw VolumeDiscoveryFailed("mock inventory");
volume->VirtualDevice=DevicePath(); volume->MountPoint=DirectoryPath();
}
shared_ptr<VolumeInfo> ValidateMountedVolume(shared_ptr<VolumeInfo> volume) const { ++CapturedReads; return volume; }
};
"""
tests = r"""
static void Require(bool condition,const char *message) { if(!condition)throw std::runtime_error(message); }
int Run() {
auto volume=MakeVolume(); CoreMacOSX core;
FailPreflight=true;
try { core.DismountVolume(volume); throw std::runtime_error("preflight ignored"); }
catch(MountServiceUnavailable &) {}
Require(Discoveries==0 && Requests==0, "operation after failed preflight");
FailPreflight=false; FailDiscovery=true;
try { core.DismountVolume(volume); throw std::runtime_error("unknown inventory ignored"); }
catch(VolumeDiscoveryFailed &) {}
Require(Requests==0, "unmounted with unknown image ownership");
FailDiscovery=false;
try { core.DismountVolume(volume); throw std::runtime_error("cleanup reported as complete"); }
catch(DismountServiceCleanupFailed &e) {
Require(e.GetSubject().find(L"pid=1234, auxiliary mount=/in-memory")!=std::wstring::npos, "cleanup error lost service details");
}
Require(!Mounted && Requests==1 && Waits==1, "service exit was not awaited after SMB removal");
Mounted=true; FailWait=false; Request=RequestLostAfterUnmount;
try { core.DismountVolume(volume); throw std::runtime_error("lost request after SMB removal reported as complete"); }
catch(DismountServiceCleanupFailed &e) {
Require(e.GetSubject().find(L"service reply lost")!=std::wstring::npos, "cleanup error lost request details");
}
Mounted=true; Request=RequestBusy;
try { core.DismountVolume(volume); throw std::runtime_error("busy auxiliary unmount reported as complete"); }
catch(MountedVolumeInUse &) {}
Require(Mounted, "busy auxiliary unmount changed the mount");
Request=RequestOk; volume->Protection=VolumeProtection::HiddenVolumeReadOnly;
core.DismountVolume(volume);
Require(CapturedReads==1 && !Mounted && Commands==0, "hidden-protection refresh did not use captured volume");
std::cout << "PASS: preflight/discovery failures stop teardown, unconfirmed exits keep details, busy SMB stays retryable, per-volume hidden-protection refresh\n";
return 0;
}
}
int main() { try { return VeraCrypt::Run(); } catch(std::exception &e) { std::cerr<<e.what()<<'\n'; return 1; } }
"""
with tempfile.TemporaryDirectory(prefix="vc-cleanup-unit-") as temporary:
work = Path(temporary)
unit = work / "cleanup.cpp"
unit.write_text(prelude + dismount + "\nstatic shared_ptr<VolumeInfo> MakeVolume() {\n" + fixture + "\nreturn volume;\n}\n" + tests)
command = ["clang++", "-std=c++11", "-DTC_UNIX", "-DTC_MACOSX", "-DVC_MACOSX_FUSET"]
command += ["-I" + str(ROOT / p) for p in ("src", "src/Crypto", "src/Common", "src/Crypto/Argon2/include")]
command += [str(unit)] + [str(args.build_dir.resolve() / name) for name in ("Core/Core.a", "Volume/Volume.a", "Platform/Platform.a")]
command += ["-Wl,-dead_strip", "-o", str(work / "cleanup")]
subprocess.run(command, check=True)
subprocess.run([str(work / "cleanup")], check=True, timeout=20)
ipc_command = ["clang++", "-std=c++11", "-DTC_UNIX", "-DTC_MACOSX"]
ipc_command += ["-I" + str(ROOT / p) for p in ("src", "src/Crypto", "src/Common", "src/Crypto/Argon2/include")]
ipc_command += [str(ROOT / "Tests/macos_cleanup_state_test.cpp")]
# The test references no other symbol from the object that registers core
# exception types for IPC, so the archive alone would not link it.
ipc_command += [str(args.build_dir.resolve() / name) for name in ("Core/CoreException.o", "Core/Core.a", "Volume/Volume.a", "Platform/Platform.a")]
ipc_command += ["-Wl,-dead_strip", "-o", str(work / "ipc")]
subprocess.run(ipc_command, check=True)
subprocess.run([str(work / "ipc")], check=True, timeout=20)
check_rollback(work, args.build_dir)
check_dismount_reporting(work, args.build_dir)
if __name__ == "__main__":
main()
+5 -2
View File
@@ -217,8 +217,11 @@ class DismountChecks:
with (self.active["aux"] / "control").open("rb") as held:
held.read(1)
result = self.vc(label + "-refused", "--unmount", self.volume, expected=1)
if "MountedVolumeInUse" not in result.stdout + result.stderr:
raise AssertionError("Busy unmount did not use MountedVolumeInUse")
# CLI errors are localized. Check the refusal and retained
# service instead of its internal C++ exception name.
os.kill(self.active["pid"], 0)
if not any(f" on {self.active['aux']} (" in line for line in self.mounted_paths()):
raise AssertionError("Busy unmount removed the auxiliary mount")
else:
self.run(label + "-detach", ["/usr/bin/hdiutil", "detach", old_device])
try:
+148
View File
@@ -0,0 +1,148 @@
#!/usr/bin/env python3
"""Unit checks for macOS discovery; no mounted volumes or sudo needed.
Compiles the production plist helpers and batch-refresh methods with a fake
inventory provider, so tests can supply incomplete inventories safely. Optional
--platform-archive runs the real bounded process runner from a matching build.
"""
import argparse
from pathlib import Path
import plistlib
import subprocess
import tempfile
ROOT = Path(__file__).resolve().parents[1]
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--platform-archive", type=Path)
args = parser.parse_args()
with tempfile.TemporaryDirectory(prefix="vc-discovery-unit-") as temporary:
work = Path(temporary)
image = work / ".veracrypt_aux_mnt-test" / "volume.dmg"
image.parent.mkdir()
image.touch()
alias = work / "path-alias"
alias.symlink_to(work, target_is_directory=True)
exact = dict(**{"image-path": str(image.resolve()), "system-entities": [{"dev-entry": "/dev/disk42", "mount-point": "/Volumes/unit"}]})
alias_image = dict(exact, **{"image-path": str(alias / image.relative_to(work))})
unknown_alias = dict(exact, **{"image-path": str(work / "missing" / image.parent.name / image.name)})
cases = {
"exact": {"images": [exact]},
"alias": {"images": [alias_image]},
"absent": {"images": []},
"unrelated": {"images": [{"image-path": "/offline/unrelated.dmg"}]},
"exact_after_unknown": {"images": [unknown_alias, {}, exact]},
"unknown_alias": {"images": [unknown_alias]},
"unknown_record": {"images": [{}]},
"bad_entities": {"images": [{"image-path": str(image.resolve())}]},
}
for name, contents in cases.items():
(work / name).write_bytes(plistlib.dumps(contents))
(work / "broken").write_text("invalid plist")
source = (ROOT / "src/Core/Unix/MacOSX/CoreMacOSX.cpp").read_text()
helpers = source[source.index("\tclass CFHolder"):source.index("\tstatic bool AuxiliaryControlFileHasVirtualDevice")]
refresh = source[source.index("\tstatic void ClearDiskImageInfo"):source.index("\t// Strict /dev/diskN")]
prelude = r'''
#include "Platform/Finally.h"
#include <CoreFoundation/CoreFoundation.h>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <algorithm>
#include <cstdlib>
#define throw_sys_sub_if(condition, subject) do { if (condition) throw std::runtime_error(subject); } while(false)
using DevicePath = std::string;
struct DirectoryPath : std::string {
using std::string::string;
DirectoryPath() {}
DirectoryPath(const std::string &s) : std::string(s) {}
bool IsEmpty() const { return empty(); }
};
struct ParameterIncorrect : std::runtime_error { ParameterIncorrect(const std::string &s) : std::runtime_error(s) {} };
struct VolumeDiscoveryFailed : std::runtime_error { VolumeDiscoveryFailed(const std::string &s, const std::wstring &) : std::runtime_error(s) {} };
struct StringConverter {
static std::string Trim(std::string s) { size_t b=s.find_first_not_of(" \t\r\n"); if(b==std::string::npos)return ""; return s.substr(b,s.find_last_not_of(" \t\r\n")-b+1); }
static std::wstring ToExceptionString(const std::exception &) { return L"failure"; }
};
static std::string Inventory;
static int Queries;
struct Process { static std::string ExecuteBounded(const std::string &, const std::list<std::string> &, int deadline) { if(deadline!=2000)throw std::runtime_error("discovery deadline"); ++Queries; return Inventory; } };
struct FuseService { static std::string GetVolumeImagePath() { return "/volume.dmg"; } };
struct SystemLog { static void WriteException(const std::exception &) {} };
#define foreach(declaration, collection) for (declaration : collection)
struct VolumeInfo {
enum DiscoveryState { DiscoveryUnknown, ImageAttached, ImageAbsent, ControlUnavailable };
DiscoveryState Discovery = DiscoveryUnknown;
DirectoryPath AuxMountPoint, MountPoint;
DevicePath VirtualDevice;
};
using VolumeInfoList = std::list<std::shared_ptr<VolumeInfo>>;
struct MountedFilesystem { DirectoryPath MountPoint; };
using MountedFilesystemList = std::list<std::shared_ptr<MountedFilesystem>>;
class CoreMacOSX {
public:
void UpdateMountedVolumesInfo(VolumeInfoList &) const;
void UpdateMountedVolumeInfo(std::shared_ptr<VolumeInfo>) const;
void UpdateMountedVolumeInfo(std::shared_ptr<VolumeInfo>, const std::string &) const;
MountedFilesystemList GetMountedFilesystems(const DevicePath &) const { return {}; }
};
'''
# Production path types expose IsEmpty(); keep that interface in the mock.
prelude = prelude.replace("using DevicePath = std::string;", "")
prelude = prelude.replace("struct ParameterIncorrect", "using DevicePath = DirectoryPath;\nstruct ParameterIncorrect")
tests = r'''
static void Require(bool condition, const char *message) { if(!condition)throw std::runtime_error(message); }
static std::string Read(const std::string &path) { std::ifstream f(path); return std::string(std::istreambuf_iterator<char>(f), {}); }
int main(int argc, char **argv) {
try {
std::string root=argv[1], image=argv[2];
for (const auto &name : {"exact", "alias", "exact_after_unknown"}) {
DevicePath device; DirectoryPath mount;
Require(FindDiskImageInfoByImagePath(Read(root+"/"+name),image,device,mount), "positive match lost");
Require(device=="/dev/disk42" && mount=="/Volumes/unit", "wrong mapping");
}
for (const auto &name : {"absent", "unrelated"}) {
DevicePath device; DirectoryPath mount;
Require(!FindDiskImageInfoByImagePath(Read(root+"/"+name),image,device,mount), "false match");
}
for (const auto &name : {"unknown_alias", "unknown_record", "bad_entities", "broken"}) {
bool failed=false; DevicePath device; DirectoryPath mount;
try { FindDiskImageInfoByImagePath(Read(root+"/"+name),image,device,mount); }
catch(std::exception &) { failed=true; }
Require(failed, "unknown inventory treated as absent");
}
VolumeInfoList volumes;
for(int i=0;i<3;++i) { auto volume=std::make_shared<VolumeInfo>(); volume->AuxMountPoint=image.substr(0,image.rfind('/')); volumes.push_back(volume); }
CoreMacOSX core;
Queries=0; Inventory=Read(root+"/exact"); core.UpdateMountedVolumesInfo(volumes);
Require(Queries==1, "more than one inventory per enumeration");
for(auto volume:volumes)Require(volume->Discovery==VolumeInfo::ImageAttached, "attached status");
Inventory=Read(root+"/broken"); core.UpdateMountedVolumesInfo(volumes);
for(auto volume:volumes)Require(volume->Discovery==VolumeInfo::DiscoveryUnknown && volume->VirtualDevice.empty() && volume->MountPoint.empty(), "stale device survived failure");
Inventory=Read(root+"/absent"); core.UpdateMountedVolumesInfo(volumes);
for(auto volume:volumes)Require(volume->Discovery==VolumeInfo::ImageAbsent, "absent status");
Inventory=Read(root+"/exact"); core.UpdateMountedVolumeInfo(volumes.front());
Require(Queries==4 && volumes.front()->VirtualDevice=="/dev/disk42", "destructive lookup reused display snapshot");
std::cout << "PASS: exact/alias matches, unrelated and incomplete inventories, batch query count, unknown/absent states, fresh lookup\n";
} catch(std::exception &e) { std::cerr << e.what() << '\n'; return 1; }
}
'''
unit = work / "discovery.cpp"
unit.write_text(prelude + helpers + refresh + tests)
command = ["clang++", "-std=c++11", "-I" + str(ROOT / "src"), str(unit), "-framework", "CoreFoundation", "-o", str(work / "discovery")]
subprocess.run(command, check=True)
subprocess.run([str(work / "discovery"), str(work), str(image)], check=True, timeout=20)
if args.platform_archive:
command = ["clang++", "-std=c++11", "-DTC_UNIX", "-DTC_MACOSX", "-I" + str(ROOT / "src"), str(ROOT / "Tests/macos_process_test.cpp"), str(args.platform_archive.resolve()), "-Wl,-dead_strip", "-o", str(work / "process")]
subprocess.run(command, check=True)
subprocess.run([str(work / "process")], check=True, timeout=20)
command = ["clang++", "-std=c++11", "-DTC_UNIX", "-DTC_MACOSX", "-I" + str(ROOT / "src"), str(ROOT / "Tests/macos_volume_state_test.cpp"), str(args.platform_archive.resolve()), "-Wl,-dead_strip", "-o", str(work / "state")]
subprocess.run(command, check=True)
subprocess.run([str(work / "state")], check=True, timeout=20)
if __name__ == "__main__":
main()
+120
View File
@@ -0,0 +1,120 @@
#!/usr/bin/env python3
"""Inactivity auto-dismount in the background GUI; no sudo required.
Requires a logged-in macOS desktop and no other VeraCrypt processes or mounts.
Two disposable containers are mounted without a filesystem, so nothing else
reads or writes them. The GUI's automatic unmount of the first volume must not
restart the idle timer of the second. Takes about two minutes.
"""
import argparse
import os
from pathlib import Path
import plistlib
import shutil
import subprocess
import tempfile
import time
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--binary", required=True, type=Path)
parser.add_argument("--keep-artifacts", action="store_true")
args = parser.parse_args()
binary = args.binary.resolve(strict=True)
mounts = lambda: subprocess.check_output(["/sbin/mount"], text=True)
if ".veracrypt_aux_mnt" in mounts():
raise RuntimeError("Dismount existing VeraCrypt volumes before this isolated GUI test")
processes = subprocess.check_output(["/bin/ps", "-axo", "comm="], text=True)
if any(Path(line.strip()).name.lower() == "veracrypt" for line in processes.splitlines()):
raise RuntimeError("Close other VeraCrypt processes before this isolated GUI test")
root = Path(tempfile.mkdtemp(prefix="vc-gui-inactivity-")).resolve()
print("Artifacts:", root, flush=True)
temporary = root / "tmp"
config = root / "config" / "VeraCrypt"
temporary.mkdir(mode=0o700)
config.mkdir(parents=True)
prefs = dict(BackgroundTaskEnabled=1, CloseBackgroundTaskOnNoVolumes=1, DismountOnInactivity=1,
MaxVolumeIdleTime=1, ForceAutoDismount=1, DismountOnLogOff=0, WipeCacheOnAutoDismount=0,
MountFavoritesOnLogon=0, MountDevicesOnLogon=0, OpenExplorerWindowAfterMount=0, SaveHistory=0)
(config / "Configuration.xml").write_text("<VeraCrypt><configuration>" + "".join(
f'<config key="{key}">{value}</config>' for key, value in prefs.items()
) + "</configuration></VeraCrypt>")
env = dict(os.environ, TMPDIR=str(temporary) + "/", XDG_CONFIG_HOME=str(root / "config"))
contents = root / "VeraCryptTest.app" / "Contents"
executable = contents / "MacOS" / "VeraCrypt"
executable.parent.mkdir(parents=True)
shutil.copy2(binary, executable)
(contents / "Info.plist").write_bytes(plistlib.dumps(dict(
CFBundleExecutable="VeraCrypt", CFBundleName="VeraCrypt Inactivity Test",
CFBundleIdentifier=f"org.idrix.veracrypt.inactivity-test.{os.getpid()}",
CFBundlePackageType="APPL", NSHighResolutionCapable=True)))
password = "Disposable-inactivity-only"
volumes = {name: root / f"{name}.hc" for name in ("first", "second")}
gui = None
succeeded = False
def vc(label, *options):
result = subprocess.run([str(binary), "--text", "--non-interactive", *map(str, options)],
env=env, capture_output=True, text=True, timeout=90)
(root / (label + ".log")).write_text(result.stdout + result.stderr)
if result.returncode:
raise RuntimeError(f"{label} failed; see {root / (label + '.log')}")
def aux_mounts():
return {line for line in mounts().splitlines() if str(temporary) in line and ".veracrypt_aux_mnt" in line}
def mount(name):
before = aux_mounts()
vc("mount-" + name, "--mount", volumes[name], "--filesystem=none", "--password=" + password,
"--pim=1", "--keyfiles=", "--protect-hidden=no")
added = aux_mounts() - before
assert len(added) == 1, "Expected one new auxiliary mount"
return added.pop()
try:
for name, volume in volumes.items():
vc("create-" + name, "--create", volume, "--size=33554432", "--volume-type=normal",
"--encryption=AES", "--hash=sha512", "--filesystem=FAT", "--password=" + password,
"--pim=1", "--keyfiles=", "--random-source=/dev/urandom")
first = mount("first")
with (root / "gui.log").open("w") as log:
gui = subprocess.Popen([str(executable), "--background-task"], env=env,
stdout=log, stderr=log, start_new_session=True)
start = time.monotonic()
time.sleep(30)
second = mount("second")
second_mounted = time.monotonic()
gone = {}
while time.monotonic() - start < 150 and len(gone) < 2:
current = aux_mounts()
for name, line in (("first", first), ("second", second)):
if name not in gone and line not in current:
gone[name] = time.monotonic()
time.sleep(0.5)
assert "first" in gone, "First idle volume was not unmounted automatically"
assert "second" in gone, "Second idle volume was not unmounted automatically"
idle = gone["second"] - second_mounted
print(f"first unmounted after {gone['first'] - start:.0f} s; second after {idle:.0f} s idle", flush=True)
# One minute limit plus discovery and timer granularity. A restarted
# timer would add the time between the two mounts (about 30 s).
assert idle < 80, "Automatic unmount of one volume restarted another volume's idle timer"
assert gui.wait(timeout=20) == 0, "Background app did not exit cleanly"
succeeded = True
print("PASS: independent idle timers, automatic unmounts, automatic exit", flush=True)
finally:
if gui and gui.poll() is None:
gui.terminate()
gui.wait(timeout=10)
for name, volume in volumes.items():
if aux_mounts():
subprocess.run([str(binary), "--text", "--non-interactive", "--unmount", str(volume)],
env=env, capture_output=True, text=True, timeout=90)
if succeeded and not args.keep_artifacts:
assert not aux_mounts(), "Disposable mount remains"
shutil.rmtree(root)
if __name__ == "__main__":
main()
+130
View File
@@ -0,0 +1,130 @@
#!/usr/bin/env python3
"""Ordinary FUSE-T container and background GUI lifecycle; no sudo required.
Requires a logged-in macOS desktop and no other VeraCrypt processes or mounts.
Uses only a disposable container, isolated preferences, and a local app bundle.
No fault injection, device reassignment, or forced unmount is performed.
"""
import argparse
import hashlib
import os
from pathlib import Path
import plistlib
import shutil
import subprocess
import tempfile
import time
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--binary", required=True, type=Path)
parser.add_argument("--keep-artifacts", action="store_true")
args = parser.parse_args()
binary = args.binary.resolve(strict=True)
mounts = lambda: subprocess.check_output(["/sbin/mount"], text=True)
if ".veracrypt_aux_mnt" in mounts():
raise RuntimeError("Dismount existing VeraCrypt volumes before this isolated GUI test")
processes = subprocess.check_output(["/bin/ps", "-axo", "comm="], text=True)
if any(Path(line.strip()).name.lower() == "veracrypt" for line in processes.splitlines()):
raise RuntimeError("Close other VeraCrypt processes before this isolated GUI test")
root = Path(tempfile.mkdtemp(prefix="vc-gui-lifecycle-")).resolve()
print("Artifacts:", root, flush=True)
temporary = root / "tmp"
mountpoint = root / "mount"
config = root / "config" / "VeraCrypt"
temporary.mkdir(mode=0o700)
mountpoint.mkdir()
config.mkdir(parents=True)
prefs = dict(BackgroundTaskEnabled=1, CloseBackgroundTaskOnNoVolumes=1,
DismountOnInactivity=0, DismountOnLogOff=1, DismountOnPowerSaving=0,
MountFavoritesOnLogon=0, MountDevicesOnLogon=0,
OpenExplorerWindowAfterMount=0, SaveHistory=0)
(config / "Configuration.xml").write_text("<VeraCrypt><configuration>" + "".join(
f'<config key="{key}">{value}</config>' for key, value in prefs.items()
) + "</configuration></VeraCrypt>")
env = dict(os.environ, TMPDIR=str(temporary) + "/", XDG_CONFIG_HOME=str(root / "config"))
contents = root / "VeraCryptTest.app" / "Contents"
executable = contents / "MacOS" / "VeraCrypt"
executable.parent.mkdir(parents=True)
shutil.copy2(binary, executable)
(contents / "Info.plist").write_bytes(plistlib.dumps(dict(
CFBundleExecutable="VeraCrypt", CFBundleName="VeraCrypt Lifecycle Test",
CFBundleIdentifier=f"org.idrix.veracrypt.lifecycle-test.{os.getpid()}",
CFBundlePackageType="APPL", NSHighResolutionCapable=True)))
volume = root / "ordinary.hc"
password = "Disposable-normal-lifecycle-only"
gui = None
active = None
succeeded = False
def vc(label, *options):
result = subprocess.run([str(binary), "--text", "--non-interactive", *map(str, options)],
env=env, capture_output=True, text=True, timeout=90)
(root / (label + ".log")).write_text(result.stdout + result.stderr)
if result.returncode:
raise RuntimeError(f"{label} failed; see {root / (label + '.log')}")
def mount(read_only=False):
nonlocal active
vc("mount", "--mount", volume, mountpoint, "--password=" + password,
"--pim=1", "--keyfiles=", "--protect-hidden=no",
*(["--mount-options=ro"] if read_only else []))
identities = list(temporary.glob(".veracrypt_aux_mnt*/shutdown"))
assert len(identities) == 1, "Expected one disposable FUSE-T service"
aux = identities[0].parent
active = (int(identities[0].read_text().split()[0]), aux,
Path((aux / "shutdown-socket").read_text().strip()))
def confirm_closed():
if active:
pid, aux, endpoint = active
try:
os.kill(pid, 0)
except ProcessLookupError:
pass
else:
raise AssertionError("Disposable service still running")
assert not aux.exists() and not endpoint.exists(), "Cleanup paths remain"
assert str(root) not in mounts(), "Disposable mount remains"
handles = subprocess.run(["/usr/sbin/lsof", "-t", str(volume)], capture_output=True, text=True)
assert handles.returncode == 1 and not handles.stdout.strip(), "Backing file still open"
try:
vc("create", "--create", volume, "--size=33554432", "--volume-type=normal",
"--encryption=AES", "--hash=sha512", "--filesystem=FAT", "--password=" + password,
"--pim=1", "--keyfiles=", "--random-source=/dev/urandom")
mount()
payload = bytes(range(256)) * 4096
with (mountpoint / "payload.bin").open("wb") as stream:
stream.write(payload)
stream.flush()
os.fsync(stream.fileno())
vc("unmount-write", "--unmount", volume)
confirm_closed()
mount(read_only=True)
assert hashlib.sha256((mountpoint / "payload.bin").read_bytes()).digest() == hashlib.sha256(payload).digest()
with (root / "gui.log").open("w") as log:
gui = subprocess.Popen([str(executable), "--background-task"], env=env,
stdout=log, stderr=log, start_new_session=True)
time.sleep(5)
assert gui.poll() is None, "Background app exited with a mounted volume"
vc("unmount-readonly", "--unmount", volume)
assert gui.wait(timeout=20) == 0, "Background app did not exit cleanly"
confirm_closed()
succeeded = True
print("PASS: payload integrity, initial background discovery, external-dismount refresh, automatic exit, service/file cleanup", flush=True)
finally:
if gui and gui.poll() is None:
gui.terminate()
gui.wait(timeout=10)
if str(root) in mounts():
vc("test-cleanup", "--unmount", volume)
if succeeded and not args.keep_artifacts:
confirm_closed()
shutil.rmtree(root)
if __name__ == "__main__":
main()
+190
View File
@@ -0,0 +1,190 @@
#!/usr/bin/env python3
"""Automatic GUI unmounts while a volume's service is slow; no sudo required.
Requires a logged-in macOS desktop, clang, an unsigned local build, and no other
VeraCrypt processes or mounts. Disposable containers are mounted without a
filesystem; fuset_startup_faults.c slows down only their own services.
1. A normal quit request (the quit Apple event also sent by logout) arrives while
an automatic unmount is in progress. It must be honored afterwards, including
unmount on quit for the remaining volume.
2. An automatic unmount cannot confirm that the service exited. The background
application must keep a warning (shown on screen until the test ends) instead
of exiting silently.
Takes about three minutes.
"""
import argparse
import os
from pathlib import Path
import plistlib
import shutil
import signal
import subprocess
import tempfile
import time
QUIT_SOURCE = r"""
#import <AppKit/AppKit.h>
#include <stdlib.h>
int main (int argc, char **argv)
{
@autoreleasepool {
NSRunningApplication *app = argc > 1 ? [NSRunningApplication runningApplicationWithProcessIdentifier:atoi (argv[1])] : nil;
return app && [app terminate] ? 0 : 1;
}
}
"""
class Leg:
def __init__(self, parent, name, prefs):
self.parent, self.name = parent, name
self.root = parent / name
self.temporary = self.root / "tmp"
config = self.root / "config" / "VeraCrypt"
self.temporary.mkdir(parents=True, mode=0o700)
config.mkdir(parents=True)
defaults = dict(BackgroundTaskEnabled=1, DismountOnInactivity=1, MaxVolumeIdleTime=1, ForceAutoDismount=1,
WipeCacheOnAutoDismount=0, WipeCacheOnClose=0, MountFavoritesOnLogon=0,
MountDevicesOnLogon=0, OpenExplorerWindowAfterMount=0, SaveHistory=0)
defaults.update(prefs)
(config / "Configuration.xml").write_text("<VeraCrypt><configuration>" + "".join(
f'<config key="{key}">{value}</config>' for key, value in defaults.items()
) + "</configuration></VeraCrypt>")
self.env = dict(os.environ, TMPDIR=str(self.temporary) + "/", XDG_CONFIG_HOME=str(self.root / "config"))
self.gui = None
self.volumes = []
def vc(self, binary, label, *options, extra=None):
result = subprocess.run([str(binary), "--text", "--non-interactive", *map(str, options)],
env=dict(self.env, **(extra or {})), capture_output=True, text=True, timeout=90)
(self.root / (label + ".log")).write_text(result.stdout + result.stderr)
if result.returncode:
raise RuntimeError(f"{label} failed; see {self.root / (label + '.log')}")
def aux_mounts(self):
mounts = subprocess.check_output(["/sbin/mount"], text=True)
return {line for line in mounts.splitlines() if str(self.temporary) in line and ".veracrypt_aux_mnt" in line}
def mount(self, binary, name, password, faults=None):
volume = self.root / (name + ".hc")
self.vc(binary, "create-" + name, "--create", volume, "--size=33554432", "--volume-type=normal",
"--encryption=AES", "--hash=sha512", "--filesystem=FAT", "--password=" + password,
"--pim=1", "--keyfiles=", "--random-source=/dev/urandom")
before = self.aux_mounts()
self.vc(binary, "mount-" + name, "--mount", volume, "--filesystem=none", "--password=" + password,
"--pim=1", "--keyfiles=", "--protect-hidden=no", extra=faults)
added = self.aux_mounts() - before
assert len(added) == 1, "Expected one new auxiliary mount"
self.volumes.append(volume)
return added.pop()
def start_gui(self, bundle):
with (self.root / "gui.log").open("w") as log:
self.gui = subprocess.Popen([str(bundle), "--background-task"], env=self.env,
stdout=log, stderr=log, start_new_session=True)
return time.monotonic()
def cleanup(self, binary):
if self.gui and self.gui.poll() is None:
self.gui.send_signal(signal.SIGTERM)
try:
self.gui.wait(timeout=10)
except subprocess.TimeoutExpired:
self.gui.kill()
self.gui.wait(timeout=10)
for volume in self.volumes:
if self.aux_mounts():
subprocess.run([str(binary), "--text", "--non-interactive", "--unmount", str(volume)],
env=self.env, capture_output=True, text=True, timeout=90)
def wait_for(condition, timeout):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if condition():
return True
time.sleep(0.2)
return condition()
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--binary", required=True, type=Path)
parser.add_argument("--keep-artifacts", action="store_true")
args = parser.parse_args()
binary = args.binary.resolve(strict=True)
if ".veracrypt_aux_mnt" in subprocess.check_output(["/sbin/mount"], text=True):
raise RuntimeError("Dismount existing VeraCrypt volumes before this isolated GUI test")
processes = subprocess.check_output(["/bin/ps", "-axo", "comm="], text=True)
if any(Path(line.strip()).name.lower() == "veracrypt" for line in processes.splitlines()):
raise RuntimeError("Close other VeraCrypt processes before this isolated GUI test")
root = Path(tempfile.mkdtemp(prefix="vc-gui-teardown-")).resolve()
print("Artifacts:", root, flush=True)
contents = root / "VeraCryptTest.app" / "Contents"
bundle = contents / "MacOS" / "VeraCrypt"
bundle.parent.mkdir(parents=True)
shutil.copy2(binary, bundle)
(contents / "Info.plist").write_bytes(plistlib.dumps(dict(
CFBundleExecutable="VeraCrypt", CFBundleName="VeraCrypt Teardown Test",
CFBundleIdentifier=f"org.idrix.veracrypt.teardown-test.{os.getpid()}",
CFBundlePackageType="APPL", NSHighResolutionCapable=True)))
faults = root / "service-faults.dylib"
subprocess.run(["/usr/bin/xcrun", "clang", "-dynamiclib", "-Wall", "-Wextra", "-O2",
str(Path(__file__).with_name("fuset_startup_faults.c")), "-o", str(faults)], check=True)
quit_tool = root / "quit-application"
subprocess.run(["/usr/bin/xcrun", "clang", "-x", "objective-c", "-fobjc-arc", "-framework", "AppKit",
"-", "-o", str(quit_tool)], input=QUIT_SOURCE, text=True, check=True)
password = "Disposable-teardown-only"
legs = []
succeeded = False
try:
# 1. Quit request during an automatic unmount.
leg = Leg(root, "quit", dict(CloseBackgroundTaskOnNoVolumes=0, DismountOnLogOff=1))
legs.append(leg)
marker = leg.root / "unmount-started"
slow = leg.mount(binary, "slow", password, dict(
DYLD_INSERT_LIBRARIES=str(faults), VC_FUSET_TEST_FAULT="unmount-delay", VC_FUSET_TEST_DELAY="8",
VC_FUSET_TEST_ROOT=str(root), VC_FUSET_TEST_FAULT_MARKER=str(marker)))
started = leg.start_gui(bundle)
time.sleep(30)
other = leg.mount(binary, "other", password)
other_idle_deadline = time.monotonic() + 60
assert wait_for(marker.exists, 120), "Automatic unmount did not start"
subprocess.run([str(quit_tool), str(leg.gui.pid)], check=True)
assert wait_for(lambda: leg.gui.poll() is not None, 40), "Quit request during an automatic unmount was not honored"
exited = time.monotonic()
assert leg.gui.returncode == 0, "Application did not exit cleanly after the quit request"
remaining = leg.aux_mounts() & {slow, other}
assert not remaining, "Volumes remained mounted after quit"
assert exited < other_idle_deadline, "The remaining volume was not unmounted by the quit request"
print(f"quit honored {exited - started:.0f} s after GUI start; both volumes unmounted", flush=True)
# 2. Automatic unmount whose service exit cannot be confirmed.
leg = Leg(root, "unconfirmed", dict(CloseBackgroundTaskOnNoVolumes=1, DismountOnLogOff=0))
legs.append(leg)
slow = leg.mount(binary, "slow", password, dict(
DYLD_INSERT_LIBRARIES=str(faults), VC_FUSET_TEST_FAULT="cleanup-delay", VC_FUSET_TEST_DELAY="15",
VC_FUSET_TEST_ROOT=str(root), VC_FUSET_TEST_FAULT_MARKER=str(leg.root / "cleanup-delayed")))
service = int(next(leg.temporary.glob(".veracrypt_aux_mnt*/shutdown")).read_text().split()[0])
leg.start_gui(bundle)
assert wait_for(lambda: slow not in leg.aux_mounts(), 120), "Automatic unmount did not start"
service_alive = lambda: subprocess.run(["/bin/kill", "-0", str(service)], capture_output=True).returncode == 0
assert wait_for(lambda: not service_alive(), 40), "Delayed service did not exit"
time.sleep(8)
assert leg.gui.poll() is None, \
f"Background application exited (status {leg.gui.returncode}) after an unconfirmed cleanup"
print("unconfirmed cleanup kept the background application and its warning", flush=True)
succeeded = True
print("PASS: quit during automatic unmount, unmount on quit, unconfirmed cleanup warning", flush=True)
finally:
for leg in legs:
leg.cleanup(binary)
if succeeded and not args.keep_artifacts:
assert not any(leg.aux_mounts() for leg in legs), "Disposable mount remains"
shutil.rmtree(root)
if __name__ == "__main__":
main()
+12
View File
@@ -34,6 +34,18 @@
<div class="wikidoc">
<h1>Release Notes</h1>
<p><strong>Unreleased changes</strong></p>
<ul>
<li><strong>Linux, macOS and BSD:</strong> Non-interactive unmount commands return a nonzero exit status when a busy volume cannot be unmounted. Scripts should check the exit status before treating a volume as locked.</li>
<li><strong>macOS:</strong>
<ul>
<li>Improve FUSE-T startup rollback and unmount cleanup, and report when service termination cannot be confirmed.</li>
<li>Keep volume status refresh and interactive unmount waits off the main window thread, and limit disk-image inventory queries to one per refresh with a timeout.</li>
<li>Distinguish unavailable volume status and detached disk images in the volume list.</li>
</ul>
</li>
</ul>
<p>
<strong>Note to users who created volumes with 1.17 version of VeraCrypt or earlier: </strong><br/>
<span style="color:#ff0000;">To avoid hinting whether your volumes contain a hidden volume or not, or if you depend on plausible deniability when using hidden volumes/OS, then you must recreate both the outer and hidden volumes including system encryption and hidden OS, discarding existing volumes created prior to 1.18a version of VeraCrypt.</span></li>
+12 -2
View File
@@ -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">
+7 -6
View File
@@ -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> ();
}
+6
View File
@@ -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; }
+3
View File
@@ -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
View File
@@ -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
+5
View File
@@ -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;
+10
View File
@@ -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);
+150 -72
View File
@@ -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
+3
View File
@@ -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;
};
}
+12
View File
@@ -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
View File
@@ -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(), &current, 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 (...) { }
+2 -1
View File
@@ -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);
+9 -2
View File
@@ -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;
}
+2 -1
View File
@@ -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
View File
@@ -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);
+32 -4
View File
@@ -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;
+3
View File
@@ -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);
+172 -7
View File
@@ -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();
}
+22
View File
@@ -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
View File
@@ -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);
+1
View File
@@ -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);
+48
View File
@@ -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
+19 -2
View File
@@ -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)
+176
View File
@@ -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) {
+6
View File
@@ -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
View File
@@ -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 &);
};
}