Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions docs/FRONTENDS.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,9 @@ admitted origin passes the navigation policy (`webfront::detail::blobOriginUrl`)

| Frontend | Chooser | Download | Test injection |
| --- | --- | --- | --- |
| WebKitGTK | default `run-file-chooser` dialog (portal under Flatpak) | `download-started` / `decide-destination`: the user's XDG download folder, the page's name reduced to its last component, never overwriting (`name (1).ext`), also between downloads that run at the same time (`DownloadReservations`) | `Session::chooseFiles`, `downloadDirectory`, `downloadFinished` |
| WebKitGTK | default `run-file-chooser` dialog (portal under Flatpak) | `download-started` / `decide-destination`: the user's XDG download folder (`~/Downloads` when none is configured, never the home folder itself; leading dots are removed from names), the page's name reduced to its last component, never overwriting (`name (1).ext`), also between downloads that run at the same time (`DownloadReservations`) | `Session::chooseFiles`, `downloadDirectory`, `downloadFinished` |
| CEF (Chrome runtime) | the runtime's dialog | the runtime's download handling | `SimpleCEFClient::chooseFiles` (`CefDialogHandler::OnFileDialog`), `downloadDirectory`, `downloadFinished`. The runtime itself turns a suggested name `../x` into `_x` |
| WKWebView | `runOpenPanelWithParameters` shows an `NSOpenPanel` sheet of the window; only frames admitted by the policy | `WKDownload` (macOS 11.3+): a save panel proposes the name | `WKWebViewOptions::chooseFiles`, `downloadDirectory`, `downloadFinished` |
| WKWebView | `runOpenPanelWithParameters` shows an `NSOpenPanel` sheet of the window; only frames of the application's own origin | `WKDownload` (macOS 11.3+): a save panel proposes the name | `WKWebViewOptions::chooseFiles`, `downloadDirectory`, `downloadFinished` |
| WebView2 | the engine's native chooser | the engine's native download UI | DevTools intercepts the chooser in tests; `DownloadStarting` redirects the download to a private path |

The engines require a user gesture to open a chooser, so the native scenarios click with a real pointer event (XTest under
Expand All @@ -75,7 +75,7 @@ WebKit reduces a suggested name such as `../x.txt` to `_x.txt` before the fronte
If all 10,000 candidate names are occupied, automatic destination selection fails and cancels the download.
WKWebView writes each download in a private staging directory beside the destination. On success it installs the file;
if a destination that was free appears during the download, it preserves that file and discards the download. Failed and
cancelled downloads remove their staging directory. Installing a new destination requires hard-link support on its filesystem.
cancelled downloads remove their staging directory. A new destination is installed with a hard link, or by a copy that still refuses an existing file on filesystems without links (exFAT, network shares); a failed installation is reported on `stderr`. Staging directories left by a crash are removed after a week. Two downloads cannot target the same chosen file at once. The file chooser opens only for the application's own origin.

### Tests

Expand Down
6 changes: 6 additions & 0 deletions include/webfront/ContentPolicy.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,12 @@ class BoundContentPolicy {
return origin && (policy.allowAnyNavigation || *origin == applicationOrigin || contains(policy.navigationAllowedOrigins, *origin));
}

/// Whether `url` belongs to the application's own origin, whatever the navigation allow-list admits.
bool isApplicationOrigin(std::string_view url) const {
const auto origin = contentOrigin(url);
return origin && *origin == applicationOrigin;
}

// Popups always leave the embedded session. Only HTTP(S) is forwarded, never shell/file schemes.
template <typename Launcher>
void handlePopup(const std::string& url, bool userInitiated, Launcher&& launch) const {
Expand Down
64 changes: 59 additions & 5 deletions include/webfront/frontend/Downloads.hpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
#pragma once

#include <filesystem>
#include <cerrno>
#include <chrono>
#include <filesystem>
#include <functional>
#include <mutex>
#include <random>
Expand All @@ -22,6 +23,7 @@ namespace webfront::frontend::detail {
class DownloadStaging {
public:
explicit DownloadStaging(const std::filesystem::path& parent) {
sweepStale(parent);
#ifdef __APPLE__
auto pattern = (parent / ".webfront-download-XXXXXX").string();
std::vector<char> buffer(pattern.begin(), pattern.end());
Expand Down Expand Up @@ -56,14 +58,55 @@ class DownloadStaging {
std::filesystem::remove_all(directory, ignored);
}
[[nodiscard]] std::filesystem::path path() const { return directory / "download"; }
/**
* @brief Installs the staged file. A new target never replaces a file that appeared meanwhile.
*
* A hard link installs atomically; on a filesystem without links (exFAT, FAT, some network shares) the file is copied,
* which still refuses an existing target. A copy that failed midway is removed.
*/
bool finish(const std::filesystem::path& target, bool replace) const {
std::error_code error;
if (replace)
if (replace) {
std::filesystem::rename(path(), target, error);
else
std::filesystem::create_hard_link(path(), target, error);
return !error;
}
std::filesystem::create_hard_link(path(), target, error);
if (!error)
return true;
error.clear();
std::filesystem::copy_file(path(), target, std::filesystem::copy_options::none, error);
if (error && error != std::errc::file_exists) {
std::error_code ignored;
std::filesystem::remove(target, ignored);
}
return !error;
}

/// Removes the staging directories that a crash left in `parent` more than a week ago.
static void sweepStale(const std::filesystem::path& parent) noexcept {
try {
constexpr std::string_view prefix = ".webfront-download-";
const auto limit = std::filesystem::file_time_type::clock::now() - std::chrono::hours(24 * 7);
std::error_code error;
for (std::filesystem::directory_iterator it(parent, error), end; !error && it != end; it.increment(error)) {
const auto name = it->path().filename().string();
if (!name.starts_with(prefix))
continue;
const bool directory = it->is_directory(error);
if (error || !directory) {
error.clear(); // An unreadable entry must not stop the sweep of the next ones.
continue;
}
if (const auto written = std::filesystem::last_write_time(it->path(), error); !error && written < limit) {
std::error_code ignored;
std::filesystem::remove_all(it->path(), ignored);
}
error.clear();
}
} catch (...) {
}
}

private:
std::filesystem::path directory;
};
Expand All @@ -79,12 +122,17 @@ class DownloadStaging {
inline std::filesystem::path
uniqueDownloadPath(const std::filesystem::path& folder, std::string_view suggested, const std::function<bool(const std::filesystem::path&)>& taken = {}) {
auto name = std::filesystem::path(std::string(suggested)).filename();
// Leading dots would let a page create hidden files (".bash_login") when the folder is the home folder.
if (const auto text = name.string(); text.starts_with('.'))
name = text.substr(text.find_first_not_of('.') == std::string::npos ? text.size() : text.find_first_not_of('.'));
if (name.empty() || name == "." || name == "..")
name = "download";
auto result = folder / name;
std::error_code error;
const auto unavailable = [&](const std::filesystem::path& path) {
return std::filesystem::exists(path, error) || (taken && taken(path));
error.clear();
const bool exists = std::filesystem::exists(path, error);
return exists || error || (taken && taken(path)); // An unreadable path is not known to be free.
};
for (int index = 1; unavailable(result); ++index) {
if (index == 10'000)
Expand Down Expand Up @@ -112,6 +160,12 @@ class DownloadReservations {
return result;
}

/// Reserves exactly `path` (a destination the user chose); false if another running download already holds it.
[[nodiscard]] bool reserveExact(const std::filesystem::path& path) {
std::scoped_lock lock{mutex};
return reserved.insert(path).second;
}
Comment thread
ambroise-leclerc marked this conversation as resolved.
Resolved

void release(const std::filesystem::path& path) {
std::scoped_lock lock{mutex};
reserved.erase(path);
Expand Down
110 changes: 70 additions & 40 deletions include/webfront/frontend/WKWebView.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#include <chrono>
#include <concepts>
#include <cstdint>
#include <cstdio>
#include <filesystem>
#include <functional>
#include <map>
Expand Down Expand Up @@ -573,8 +574,8 @@ struct Session {
id result = nullptr; // NSArray<NSURL*>*; nil cancels.
bool deferred = false;
guard([&] {
// Only the frames the policy admits may open a chooser.
if (!contentPolicy.allowsNavigation(effectiveFrameUrl(frame)))
// Only the application's own origin may open a chooser, not every origin that navigation admits.
if (!contentPolicy.isApplicationOrigin(effectiveFrameUrl(frame)))
return;
if (options.chooseFiles) {
const auto files = options.chooseFiles();
Expand All @@ -594,15 +595,24 @@ struct Session {
const auto directories = send<BOOL>(parameters, "allowsDirectories");
send<void>(panel, "setCanChooseDirectories:", directories);
send<void>(panel, "setCanChooseFiles:", static_cast<BOOL>(!directories));
auto handler = Block_copy(completion);
send<void>(panel, "retain");
void (^finished)(long) = ^(long response) {
handler(response == 1 ? send(panel, "URLs") : nullptr); // NSModalResponseOK
send<void>(panel, "release");
Block_release(handler);
};
auto handler = Block_copy(completion);
bool retained = false;
try {
send<void>(panel, "retain");
retained = true;
void (^finished)(long) = ^(long response) {
handler(response == 1 ? send(panel, "URLs") : nullptr); // NSModalResponseOK
send<void>(panel, "release");
Block_release(handler);
};
send<void>(panel, "beginSheetModalForWindow:completionHandler:", window, finished);
} catch (...) {
if (retained)
send<void>(panel, "release");
Block_release(handler); // The panel never took the handler: `completion` answers below.
throw;
}
deferred = true;
send<void>(panel, "beginSheetModalForWindow:completionHandler:", window, finished);
});
if (!deferred)
completion(result);
Expand Down Expand Up @@ -637,36 +647,54 @@ struct Session {
const auto panel = send(type("NSSavePanel"), "savePanel");
Object name(text(std::filesystem::path(suggested).filename().string()));
send<void>(panel, "setNameFieldStringValue:", name.get());
auto handler = Block_copy(completion);
auto token = alive; // Not `this`: the window may close, and the session end, while the panel is open.
const id key = download; // By value: the panel answers after this lambda and its references are gone.
send<void>(panel, "retain");
void (^finished)(long) = ^(long response) {
id chosen = response == 1 ? send(panel, "URL") : nullptr; // NSModalResponseOK
if (chosen && !*token)
chosen = nullptr; // The session is gone: nobody could move the file afterwards.
try {
if (chosen) {
const std::filesystem::path target = utf8(send(chosen, "path"));
std::error_code code;
const bool replace = std::filesystem::exists(target, code);
if (code)
throw std::filesystem::filesystem_error("Cannot inspect download target", target, code);
auto staging = std::make_unique<frontend::detail::DownloadStaging>(target.parent_path());
const auto temporary = staging->path();
Object path(text(temporary.string()));
chosen = send(type("NSURL"), "fileURLWithPath:", path.get());
(*token)->downloadDestinations[key] = {std::move(staging), target, false, replace};
auto handler = Block_copy(completion);
bool retained = false;
auto token = alive; // Not `this`: the window may close, and the session end, while the panel is open.
const id key = download; // By value: the panel answers after this lambda and its references are gone.
try {
send<void>(panel, "retain");
retained = true;
void (^finished)(long) = ^(long response) {
id chosen = response == 1 ? send(panel, "URL") : nullptr; // NSModalResponseOK
if (chosen && !*token)
chosen = nullptr; // The session is gone: nobody could move the file afterwards.
try {
if (chosen) {
const std::filesystem::path target = utf8(send(chosen, "path"));
std::error_code code;
const bool replace = std::filesystem::exists(target, code);
if (code)
throw std::filesystem::filesystem_error("Cannot inspect download target", target, code);
auto& sessionReservations = (*token)->reservations;
if (!sessionReservations.reserveExact(target))
throw std::filesystem::filesystem_error("Another download is writing this target", target,
std::make_error_code(std::errc::file_exists));
try {
auto staging = std::make_unique<frontend::detail::DownloadStaging>(target.parent_path());
const auto temporary = staging->path();
Object path(text(temporary.string()));
chosen = send(type("NSURL"), "fileURLWithPath:", path.get());
(*token)->downloadDestinations[key] = {std::move(staging), target, true, replace};
} catch (...) {
sessionReservations.release(target);
throw;
}
}
} catch (const std::filesystem::filesystem_error&) {
chosen = nullptr; // No staging, or the target is taken: answer WebKit once, without crossing the AppKit block.
}
} catch (const std::filesystem::filesystem_error&) {
chosen = nullptr; // No temporary name is free: answer WebKit once, without crossing the AppKit block.
}
handler(chosen);
send<void>(panel, "release");
Block_release(handler);
};
handler(chosen);
send<void>(panel, "release");
Block_release(handler);
};
send<void>(panel, "beginSheetModalForWindow:completionHandler:", window, finished);
} catch (...) {
if (retained)
send<void>(panel, "release");
Block_release(handler); // The panel never took the handler: `completion` answers below.
throw;
}
deferred = true;
send<void>(panel, "beginSheetModalForWindow:completionHandler:", window, finished);
});
if (!deferred)
completion(result);
Expand All @@ -678,8 +706,10 @@ struct Session {
return;
const auto pending = std::move(found->second);
downloadDestinations.erase(found);
if (completed)
completed = pending.staging->finish(pending.target, pending.replace);
if (completed && !pending.staging->finish(pending.target, pending.replace)) {
completed = false;
std::fprintf(stderr, "WebFront: the download could not be installed at %s\n", pending.target.string().c_str());
}
if (pending.reserved)
reservations.release(pending.target);
if (completed && options.downloadFinished)
Expand Down
15 changes: 9 additions & 6 deletions include/webfront/frontend/WebKitGTK.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ class Api {
void (*bytesUnref)(Object) = symbol<decltype(bytesUnref)>("g_bytes_unref");
void (*errorFree)(Error*) = symbol<decltype(errorFree)>("g_error_free");
// GLib resolves the folder from user-dirs.dirs (a user may have moved it), not only from the environment.
const char* (*homeDirectory)() = symbol<decltype(homeDirectory)>("g_get_home_dir");
const char* (*userDirectory)(int) = symbol<decltype(userDirectory)>("g_get_user_special_dir"); // G_USER_DIRECTORY_DOWNLOAD = 2
void (*downloadDestination)(Object, const char*) = symbol<decltype(downloadDestination)>("webkit_download_set_destination");
void (*downloadCancel)(Object) = symbol<decltype(downloadCancel)>("webkit_download_cancel");
Expand Down Expand Up @@ -425,15 +426,17 @@ struct Session : FailureState {
std::filesystem::path destinationFolder() const {
if (!downloadDirectory.empty())
return downloadDirectory;
if (const auto* folder = a.userDirectory(2); folder && *folder)
return folder;
if (const auto* home = std::getenv("HOME"); home && *home) {
const auto* home = std::getenv("HOME");
if (!home || !*home)
home = a.homeDirectory(); // GLib reads the passwd database when HOME is unset.
if (const auto* folder = a.userDirectory(2); folder && *folder) {
std::error_code error;
const auto folder = std::filesystem::path(home) / "Downloads";
if (std::filesystem::is_directory(folder, error))
// GLib reports the home folder itself when no download folder is configured: never write there.
if (!(home && *home && std::filesystem::equivalent(folder, home, error)))
Comment thread
ambroise-leclerc marked this conversation as resolved.
Resolved
return folder;
return home;
}
if (home && *home)
return std::filesystem::path(home) / "Downloads"; // Created on demand.
return std::filesystem::temp_directory_path();
}
std::filesystem::path reserveDestination(std::string_view suggested) {
Expand Down
Loading